Django ORM: Selecting related set

后端 未结 4 1102
遥遥无期
遥遥无期 2020-12-24 13:51

Say I have 2 models:

class Poll(models.Model):
    category = models.CharField(u\"Category\", max_length = 64)
    [...]

class Choice(models.Model):
    pol         


        
4条回答
  •  自闭症患者
    2020-12-24 14:30

    Time has passed and this functionality is now available in Django 1.4 with the introduction of the prefetch_related() QuerySet function. This function effectively does what is performed by the suggested qbind function. ie. Two queries are performed and the join occurs in Python land, but now this is handled by the ORM.

    The original query request would now become:

    polls = Poll.objects.filter(category = 'foo').prefetch_related('choice_set')
    

    As is shown in the following code sample, the polls QuerySet can be used to obtain all Choice objects per Poll without requiring any further database hits:

    for poll in polls:
        for choice in poll.choice_set:
            print choice
    

提交回复
热议问题