*_set attributes on Django Models

后端 未结 4 1513
梦毁少年i
梦毁少年i 2021-02-04 03:09

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

4条回答
  •  醉话见心
    2021-02-04 03:55

    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.

提交回复
热议问题