关于foo_set.的用法

Following relationships “backward”

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager  that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO  is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the “Retrieving objects” section above.

Example:

>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.

# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains='Lennon')
>>> b.entry_set.count()

You can override the FOO_set name by setting the related_name parameter in the ForeignKey definition. For example, if the Entry model was altered to blog =ForeignKey(Blog, related_name='entries'), the above example code would look like this:

>>> b = Blog.objects.get(id=1)
>>> b.entries.all() # Returns all Entry objects related to Blog.

# b.entries is a Manager that returns QuerySets.
>>> b.entries.filter(headline__contains='Lennon')
>>> b.entries.count()

 

posted @ 2015-04-20 15:31  坐观云起时  阅读(113)  评论(0编辑  收藏  举报