Reputation: 3366
I have a ViewSet
that has a get_queryset
method. This method filters objects using a Q
object:
def get_queryset(self):
request = self.request
query = Ticket.objects.filter(
Q(message_type__users__in=[request.user])|
Q(reference__to_user=request.user)
)
return query
output:
[<Ticket: 24>, <Ticket: 24>, <Ticket: 24>, <Ticket: 24>]
it returns the same Ticket (id = 24) four times. For 'GET' requests from client, i get MultipleObjectsReturned
exception:
get() returned more than one Ticket -- it returned 4!
Why does Q object return multiple results?
Upvotes: 2
Views: 660
Reputation: 1928
Indeed, the way SQL works, it means you have 1 ticket, but either 4 message_type
or 4 reference
objects related to that ticket, so when you JOIN
, all of them will be returned.
Using .distinct()
should solve your problems.
Upvotes: 3
Reputation: 4859
This filters down to SQL: The way a query is built can result in the same row either satisfying more than one condition or satisfying the same condition more than once.
If this is the best way to format your query, try tacking on .distinct()
to avoid duplicate results.
Upvotes: 1