Understanding django

New to this and trying to learn python and django. I will go straight to the chase. I am reading a django tutorial on the main site, and I see that you can set up a database in django with class variables like the ones given here.

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

In this lesson, a survey object is created using

p = Poll(question="What new?", pub_date=timezone.now())

My question is: it seems that the strings are passed using named arguments, but in the class they are represented by objects built with models. So how do django convert the string “What's New?” To become the subject of a question?

+4
source share
3 answers

, Django. Django . , :

question = models.CharField(max_length=200)

, Poll , .

+5

, question pub_date : . Django , , , .

, Poll, models.Model, Django question pub_date , .

, ORM:

class CoolModel:
    def __init__(self, **kwargs):
        self.values = {}
        for field, value in kwargs.items():
            if getattr(self, field, None):
                self.values[field] = value
            else:
                raise Exception('Unknown model field - {}!'.format(field))

class CoolField(object):
    pass

# Here we create our model:

class Poll(CoolModel):
    name = CoolField()
    date = CoolField()

m1 = Poll(name='test', date='yesterday?')
print m1.values  # Prints '{"name": "test", "date": "yesterday"}'
m2 = Poll(name='test2', some_field="wtf") # Raises Exception:
                                               # Unknown model field = some_field!

Django.

+5

, Poll question CharField (), . Django !

+2

Source: https://habr.com/ru/post/1569420/


All Articles