Agus Mathew
Agus Mathew

Reputation: 941

Django ORM querying nested models

I want to use django ORM to filter some records from db, I have a model named User which contain a field profile which is another model, When I do the following I get all the users having a profile:

users = User.objects.filter(Q(profile__isnull=False))

profile has a field age I want to delete all the users with a profile and age>30. So I looped through all the users with a profile and then checked if their age is > 30.

for user in  users:
    if user.profile.age>30:
          user.delete()

Is there a way to use user.profile.age>30 directly in querying?

Upvotes: 1

Views: 80

Answers (1)

Agus Mathew
Agus Mathew

Reputation: 941

I solved the problem by combining Q objects from Django as followings:

User.objects.filter(Q(profile__isnull=False) & Q(profile__age__gt=30))

Upvotes: 2

Related Questions