tags:

views:

275

answers:

1

There is this line in the Django tutorial, Writing your first Django app, part 1:

    p.choice_set.create(choice='Not much', votes=0)

How is choice_set called into existence and what is it?

I suppose the choice part is the lowercase version of the model Choice used in the tutorial, but what is choice_set? Can you elaborate?


Update 1: based on Ben James' answer I located a place in the documentation where it is described: Following relationships "backward".

+5  A: 

You created a foreign key on Choice which relates each one to a Poll.

So, each Choice explicitly has a poll field, which you declared in the model.

Django's ORM follows the relationship backwards from Poll too, automatically generating a field on each instance called foo_set where Foo is the model with a ForeignKey field to that model.

choice_set is a RelatedManager which can create querysets of Choice objects which relate to the Poll instance, e.g. p.choice_set.all()

If you don't like the foo_set naming which Django chooses automatically, or if you have more than one foreign key to the same model and need to distinguish them, you can choose your own overriding name using the related_name argument to ForeignKey.

Ben James
Thanks. I know much more now. Isn't choice_set a "Manager" ? (that can return an instance of class QuerySet). Or is it the same thing?
Peter Mortensen
You're correct, it's a `RelatedManager` which can create querysets.
Ben James