I am going through the Django tutorial: https://docs.djangoproject.com/en/dev/intro/tutorial01/
And I am looking at the example of using the python shell with manage.py. Code snippet is copied from website:
# Give the Poll a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a poll's choices) which can be accessed via the API.
>>> p = Poll.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
[]
This example is using a Poll model with a question and choice of answers, defined here:
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField()
Now I don’t understand where the object choice_set comes from. For a question we have a group of “Choices”. But where is this explicitly defined? I just seems two classes are defined. Does the models.foreignKey(Poll) method connect the two classes (hence tables)?
Now where does the suffix “_set” come from in choice_set. Is it because we are implicitly defining a one-to-many relationship between the Poll and Choice tables, hence we have a “set” of choices?
choice_setis put there automatically by the Django ORM because you have a foreign key fromChoicetoPoll. This makes it easy to find all theChoices for a particularPollobject.It is hence not explicitly defined anywhere.
You can set the name of the field with the
related_nameparameter toForeignKey.