dowjones123
dowjones123

Reputation: 3847

Correct use of select_related

I currently have the following code that I want to optimize using select_related. The aim is to find out the set of BaseReward for which there is at least one Voucher with is_active = True

    class Basereward(models.Model):
        active = models.BooleanField()

    class Voucher(models.Model):
        reward = models.ForeignKey(BaseReward, related_name='reward_vouchers')
        is_active = models.BooleanField()

View

    qs = BaseReward.objects.filter(active=True).all()
    for reward in qs:
        if not reward.reward_vouchers.filter(is_active=True).all():
            qs = qs.exclude(id=reward.id)
    return qs

What is the correct way of doing it? I was thinking using the select_related using the reverse relationship, but the doc says it won't work Any other way?

    qs = BaseReward.objects.filter(active=True).all().select_related(reward_vouchers)

Upvotes: 0

Views: 1301

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174738

Do it the other way around, get the unique set of BaseReward objects for where there is at least one Voucher:

Voucher.objects.filter(is_active=True).distinct(reward)

Upvotes: 1

Related Questions