Filter a django model by comparing two foreign keys
Question: 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
    


Answer: You will have to use [F()
expressions](https://docs.djangoproject.com/en/dev/topics/db/queries/#django.db.models.F)
to do this

    
    
    from django.db.models import F
    
    match = UserProfile.objects.filter(user__date_joined__gte = F('group__date'))
    

