Mikhail
Mikhail

Reputation: 9007

Filter a django model by comparing two foreign keys

I need to create a filter in Django by comparing two foreign keys to each other. The double-underscore syntax only works on the left hand side of the equation. So whatever is on the right side throws an error:

match = UserProfile.objects.filter(
    user__date_joined__gte = group__date
)

Django (or python here) doesn't interpret group_date as a parseable variable name, and complains that it's not defined. I can switch the variables around, and then user_date_joined would be undefined. (the variable names here are just an example)

What I'm trying to achieve would look like this in SQL:

SELECT * FROM profile p, user u, group g WHERE
    p.u_id = u.id AND
    u.group_id = g.id AND
    u.date_joined >= g.date

Upvotes: 1

Views: 1221

Answers (1)

Rohan
Rohan

Reputation: 1041

You will have to use F() expressions to do this

from django.db.models import F

match = UserProfile.objects.filter(user__date_joined__gte = F('group__date'))

Upvotes: 6

Related Questions