1

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?

2
  • 3
    Try: User.objects.filter(Q(profile__isnull=False) & Q(profile__age__gt=30)) Commented Sep 4, 2020 at 8:04
  • You're welcome. Glad to hear it worked. Commented Sep 4, 2020 at 8:15

1 Answer 1

2

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

User.objects.filter(Q(profile__isnull=False) & Q(profile__age__gt=30))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.