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)