Django INNER JOIN and WHERE

Viewed 58

Let me introduce you with the structure. Let's say I have 3 models defined as:

class User(AbastractUser):
    some fields...

class UserProfile(Model):
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES, default='unknown', verbose_name=_('Gender'))
...
    user = models.OneToOneField(User, related_name='userprofile', on_delete=CASCADE)
    preferences = models.OneToOneField(
        Preferences, related_name='user_profile', null=True, on_delete=CASCADE
    )

class Preferences(TimestampedModel):
    some fields...
    method = models.CharField(
        max_length=10, null=True, blank=True, default=None, choices=[(x, x) for x in methods]
    )

I would like to write this query with django models, what would be the way?

Query:


SELECT * from users as u
INNER JOIN users_profile as up ON u.id as up.user_id
INNER JOIN preferences as p ON p.id as up.preference_id
WHERE p.method = 'TEST' 

Any suggestions, what would be the cleanest way, also most optimised?

1 Answers

You can filter with:

User.objects.filter(userprofile__preferences__method='TEST')
Related