[Answer]-How to filter related objects?

1👍

Join

GameImage.objects.filter(img_type='small_image').select_related('game')

Left join game

from django.db.models import Q

GameImage.objects.filter(
    Q(img_type='small_image') | 
    Q(game__isnull=True)
).select_related('game')

Left join game image

Game.objects.filter(
    Q(images__img_type='small_image') |
    Q(id__isnull=True)
).select_related('images')

0👍

So you want all games but want to check if the game has small_image or not without loading extra related images:

models.py:

from django.core.exceptions import ObjectDoesNotExist

Class Game(models.Model):
    title = models.CharField(max_length='255', blank=False, db_index=True)

    def get_small_image(self):
        try:
            return self.images.get(type='small_image')
        except ObjectDoesNotExist:
            return None

views.py:

games = Game.objects.all()
for game in games:
    small_image = game.get_small_image()
    if small_image:
        print small_image.image.url
    else:
        print 'there is no small image for this game'

Leave a comment