user8354377
user8354377

Reputation:

Django official tutorial models part4

I'm following djangoproject official tutorials in part 4 it use question.choice_set Statment I don't know what is mean choice_set can anyone help me?

Can I use question.Objects for example instead of question.choice_set?

Upvotes: 1

Views: 56

Answers (2)

neverwalkaloner
neverwalkaloner

Reputation: 47354

modelname_set is default attribute name by which you can access reverse related objects . So in your you have model something like:

class Question(Model):
    ...

class Choice(Model):
    question = ForeignKey(Question)
    ...

So if you want to get all choices related to specific question you can use followng syntax:

question.choice_set.all()

You can change attribute name to something more human readable using related_name argument:

class Choice(Model):
    question = ForeignKey(Question, related_name='choices')

In this case you can now use question.choices.all() to get question's choices.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

If you make a ForeignKey from Choice to Question, like:

class Choice(models.Model):
    # ...
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

Then Django automatically creates an opposite relation. By default, the name of the relation is nameofmodel_set.

Since there can be multiple Choice objects that map on the same Question, this is a set (a set that can contain zero, one, or more objects).

So by using somequestion.choice_set, you get an ObjectManager that deals with all the Choice objects for a specific Question instance (here the somequestion).

You can then for example .filter(..) on that set, or .update(..) or write custom ORM queries. So for example somequestion.choice_set.all() will give you all the related Choices.

Sometimes the name of this reverse relation is not very nice, in that case, you can use the reated_name parameter, to give it another name, like:

class Choice(models.Model):
    # ...
    question = models.ForeignKey(Question,
                                 on_delete=models.CASCADE,
                                 related_name='options')

In case you do not want such reverse relation (for example because it would result in a lot of confusion), then you can use a '+' as related_name:

class Choice(models.Model):
    # ...
    # no opposite relation
    question = models.ForeignKey(Question,
                                 on_delete=models.CASCADE,
                                 related_name='+')

Upvotes: 3

Related Questions