Maddie Graham
Maddie Graham

Reputation: 2177

Exclude fields with the same value using Django querysets

In my project, I have Articles and User Responses that have the same value "title". I only want to find the first Articles, because other object have the same "title", these are the users' answers. How can I exclude objects from queryset have the same "title" parameter.

I try this:

q1 = Article.objects.order_by().values('title').distinct()

*works good but it returns something like a list.

Well, I tried to convert it to query:

q2 = Article.objects.filter(title__in=q1).distinct()

*But it causes it to return all Repeat-Topic Articles again.

How to exclude objects from queryset that have the same title without changing them to a list?

Upvotes: 1

Views: 1143

Answers (1)

NKSM
NKSM

Reputation: 5854

On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply.

If it is your's case then the following must be work:

Article.objects.filter(title__in=q1).order_by('title').distinct('title')

Upvotes: 2

Related Questions