1

Basically I have models Image and Member and I want to preselect for each user his profile image if it exists. In pure sql, I would do this with left outer join. How to do that with django ORM?

class Media(models.Model, WebModel):
    title = models.CharField('title', max_length=128, default='', db_index=True, blank=True)
    member = models.ForeignKey(Member, null=True, default=None, related_name='member_%(class)s_set')
    profile = models.BooleanField(default=False)

    class Meta:
        abstract = True



class Image(Media):
    image = ProcessedImageField(upload_to='uploads',
                                processors=[ResizeToFit(width=1024, height=1024, upscale=False)],
                                format='JPEG',
                                options={'quality': 75})



class Member(models.Model, WebModel):
    name = models.CharField('name', max_length=64, default='')
    phone = models.CharField('phone', max_length=32, default='', blank=True)
    sex = models.IntegerField('sex', null=True, default=None, choices=sexes)

1 Answer 1

2

You use QuerySet.prefetch_related.

Unfortunately, prefetch_related doesn't support filtering (yet), and filter-ing on the Member.media_set QuerySet will create a new database query.

You have two options here:

  • Do the filtering in Python to find Media with profile == True
  • Wait for Django 1.7 and use the new Prefetch lookup object.

If you were to do the filtering in Python, you would do something like:

profile_pictures = [media for media in member.media_set.all() if media.profile]

This will be faster than querying the database if you don't have too many images. You'll want to benchmark.

2
  • can you show the query and how to access the profile image afterwards?
    – clime
    Nov 23, 2013 at 22:45
  • ye, with that code I would also need associate each profile image with its user so that is not gonna be a way. I though you will use the prefetch_related thing: user_images=User.objects.prefetch_related('member_image_set').member_image_set and profile_image=filter(lambda i: i.profile, user_images) but that would be also slow. With Prefetch('member_image_set', queryset=Image.objects.filter(profile=True)) this is gonna be much faster cause user_images will contain at most one image (no need to filter).
    – clime
    Nov 23, 2013 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.