使用Django 1.5 + django-model-utils进行prefetch_related

时间:2013-10-22 07:12:30

标签: python django django-models django-queryset prefetch

我有一个类似于以下的模型,我正在使用django-model-utils提供的InheritanceManager,它允许我查询所有子类(在这种情况下,无论TextPost或PhotoPost,我都会获得所有帖子)。

鉴于类似的情况,如何在PhotoPosts的照片和TextPost的身体上使用prefetch_related进行查询?

使用django-model-utils查询看起来有点像这样:

Post.objects.filter(user=user).select_subclasses()

-

class Post(models.Model):

    post_type = models.ForeignKey(ContentType)
    user = models.ForeignKey(User, blank=True, null=True, related_name='posts')

    objects = InheritanceManager()

    class Meta:
        app_label = 'posts'

    def save(self, *args, **kwargs):
        if not self.pk:
            self.post_type = ContentType.objects.get_for_model(type(self))
            # import pdb; pdb.set_trace()
        super(Post, self).save(*args, **kwargs)

class TextPost(Post):
    """ Text post model """
    body = models.TextField()

    class Meta:
        app_label = 'posts'


class PhotoPost(Post):
    """ Photo post model """
    photo = models.ForeignKey('posts.Photo')

    class Meta:
        app_label = 'posts'

1 个答案:

答案 0 :(得分:1)

您可以使用prefetch_related方法收集此信息。

Post.objects.filter(user=user).select_subclasses().prefetch_related('photo','bo‌​dy')