1

I'm trying to get a list of Users that have created at least one Post object. I want to do something like users = User.objects.filter(posts__not_null) How can I do this?

models.py

class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) 

Thanks!

1 Answer 1

1

You can obtain this with:

User.objects.filter(post__isnull=False).distinct()

The .distinct() [Django-doc] is useful to prevent returning the same user that much times as there are Posts for that user.

Sign up to request clarification or add additional context in comments.

1 Comment

that worked perfectly, thank you! Great explanation as well. very helpful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.