Django queryset filter equal or compared based on another column / fields within same models


There will be a case when we want to filtering data that have “equal” between one fields with another fields (column) on same models.
Given example, We have Django built-in user table called “auth_user” and user profile table called “user_profile”. The requirement is we want to get all users that not-logged and have status “GAMER” in their profile.

At this cases, that means we need to compare between “date_joined” and “last_login” column.

Here is the raw mysql:

1
Select COUNT(*) from user_profile AS t1 INNER JOIN auth_user AS t2 ON t1.user_id = t2.id AND t1.status="GAMER" AND t2.last_login = t2.date_joined;

Now, how to make it in Django queryset? Say thanks to “F” objects! Django have a lot of magic gem inside.

How to use it? Here is the example:

1
2
3
4
gamers = User.objects.filter(
             userprofile__status=’GAMER’,
             date_joined__eq=F("last_login")
         ).order_by(‘last_login’)

Easy! 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.