35
loading...
This website collects cookies to deliver better user experience
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
models.Model
. Inheriting Model
signals Django at run-time the class is a database model. Question
model(later converted to a table) contains two extra class variables, question_text
and pub_date
, which will be two columns in the table. Their type is indicated by creating an instance of the respective type of fields, here models.CharField, models.DateTimeField
. A similar work applies to the Choice model.Question
(all the rows in the table - polls_question).>>> Question.objects.all()
<QuerySet []>
objects.all()
and QuerySet
. All the data entry in and out of the database through Django ORM happens through the object's interface. All the results are wrapped inside the QuerySet, even empty ones.>>> class Foo:
... pass
...
>>> class Bar(Foo):
... pass
...
>>> Bar.mro()
[<class 'Bar'>, <class 'Foo'>, <class 'object'>]
>>> Question.mro()
[<class 'polls.models.Question'>,
<class 'django.db.models.base.Model'>,
<class 'object'>]
Question
is clear and returns result as expected.>>> Bar
<class 'Bar'>
>>> Question
<class 'polls.models.Question'>
>>> Question.objects
<django.db.models.manager.Manager object at 0x10bd7f1c0>
>>> Question.objects.mro()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Manager' object has no attribute 'mro'
>>> Question.objects.__class__.mro()
[<class 'django.db.models.manager.Manager'>, <class 'django.db.models.manager.BaseManagerFromQuerySet'>, <class 'django.db.models.manager.BaseManager'>, <class 'object'>]
Question.objects
is different from the representation of Bar
and Question
classes. As the name indicates, objects
is an instance of the Manager
. The objects
, the instance of Manager class, inherits BaseManagerFromQuerySet
and BaseManager
.>>> Choice
<class 'polls.models.Choice'>
>>> Choice.objects
<django.db.models.manager.Manager object at 0x10bd7f0a0>
>>> Question.objects
<django.db.models.manager.Manager object at 0x10bd7f1c0>
>>> Choice.objects is Question.objects
False
>>> Choice.objects == Question.objects
True
True
.# It's decalared in manager class
def __eq__(self, other):
return (
isinstance(other, self.__class__) and
self._constructor_args == other._constructor_args
)
>>> Question.objects._constructor_args
((), {})
>>> Choice.objects._constructor_args
((), {})
models.*Field
works.model.Model
and all the class variables initialized with model.*Field
automatically behaves like a column in the table.ModelManager
via objects
attribute.