I have a very basic question about django.db.models
.
In this official django tutorial, if you search for word \"choice_set
\", you will see tha
This is some ForeignKey
magic :)
The Choice
model has the attribute poll
, which is a ForeignKey
to a Poll
object. Django adds the convenience method choice_set
to Poll
objects, which will give a QuerySet
containing all Choice
objects that reference that Poll
Object.
So, given this (pseudo) code
myPoll = Poll(question='Is Django awesome?')
option_yes = Choice(poll=myPoll, choice='Yes')
option_no = Choice(poll=myPoll, choice='No')
You could later run
poll = Poll.objects.get(question='Is Django awesome?')
options = poll.choice_set.all()
and options would include the relevant Choice
objects.
You can change the name of this attribute using the related_name
option when defining the ForeignKey
.