Fohlen
Fohlen

Reputation: 296

Use a model field to query another model field in django

I have two models in our django app

class Reg(models.Model):
   transactions = ManyToMany
   price = IntegerField

class Transaction(models.Model)
   amount = IntegerField

Now I would like to make a lookup like:

Registration.objects.filter(reg__price==transaction__amount)

Previously we used the following approach:

This is ofc very query-consuming and inefficient. I wonder whether there would be a better way to do this! Any hint is appreciated :)

Upvotes: 0

Views: 2627

Answers (1)

user2390182
user2390182

Reputation: 73450

You can use an F expression for such a query:

from django.db.models import F

Registration.objects.filter(price=F('transactions__amount'))

This will filter all Registration instances whose price is equal to one of their transactions' amount. If you want all transactions amounts' sum to be equal or more than the registration price, you can use annotations to aggregate each registration's Sum:

paid_registrations = Registration.objects.\
   annotate(ta=Sum('transactions__amount')).\  # annotate with ta sum
   filter(price__lte=F('ta'))  # filter those whose price is <= that sum

Upvotes: 2

Related Questions