I have the following models:
class Donation(models.Model):
donation_amount = models.DecimalField(max_digits=9, decimal_places=2)
donor_name = models.CharField(max_length=200)
class Charge(models.Model):
donation = models.ForeignKey(Donation)
error = models.TextField(null=True, blank=True)
And I have a complex query that should do one of the following:
Get all donations or all donations which has at least one failed charge.
I came up with the following solution:
# get all donations with charge prefetched
all_donations = Donation.objects.all().prefetch_related('charge_set')
# sometimes filter for failed ones
if need_failed_charges:
all_donations = all_donations.annotate(count=Count('charge')) \
.filter(charge__error__isnull=False, count__gt=0)
Here I use the count
to track the number of charges I have per donation, I filter them afterward to check if I have at least one.
I think there is a better way to express this, but as I'm still new to the django world I cannot see it.
What do you think?