Question

I have a model similar to the following, and I'm using an InheritanceManager provided by django-model-utils which allows me to query for all subclasses (in this case, I'd get all posts regardless of TextPost or PhotoPost).

Given a similar situation, how can I query with prefetch_related on PhotoPosts's photo and TextPost's body?

Querying with django-model-utils looks a bit like this:

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'
Was it helpful?

Solution

As Andy correctly pointed out, you can use the prefetch_related method to gather this information. However, the query is slightly different. You have to prefetch on the related_name (which is hidden, when using model inheritence). Also, TextPost's body is just textfield, so you don't need to prefetch it, that's taken care of by select_subclasses

Post.objects.filter(user=user)\
    .select_subclasses()\
    .prefetch_related('photopost__photo')

OTHER TIPS

You can use the prefetch_related method to gather this information.

Post.objects.filter(user=user).select_subclasses().prefetch_related('photo','bo‌​dy')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top