Reputation: 21562
This is Django 1.4.2 running on OSX, with a PostgreSQL database.
Here's my model:
class RideRequest(models.Model):
user = models.ManyToManyField(User, related_name="ride_requests", symmetrical=False)
status = models.IntegerField(choices=STATUS_CHOICES)
In all my filter calls for this model, I get all objects twice.
[10]: queryset = RideRequest.objects.filter(id=8)
[11]: for q in queryset: print q.id
8
8
I just looked into the database, and every entry is only present once. Any ideas why this would happen? I can't easily switch to SQLite because of certain DB constraints.
Edit: Here's the raw SQL query output of RideRequest.objects.filter(id=8).query
. It too returns two rows instead of the expected one. Could it be because of the excessive JOINing that is going on?
SELECT "rides_riderequest"."id", "rides_riderequest"."ride_id",
…
FROM "rides_riderequest"
LEFT OUTER JOIN "rides_riderequest_ride_request_stations"
ON ("rides_riderequest"."id" = "rides_riderequest_ride_request_stations"."riderequest_id")
LEFT OUTER JOIN "rides_riderequeststation"
ON ("rides_riderequest_ride_request_stations"."riderequeststation_id" =
"rides_riderequeststation"."id") WHERE "rides_riderequest"."id" = 8
ORDER BY "rides_riderequeststation"."departure_time_min" DESC;
Upvotes: 0
Views: 498
Reputation: 51645
I suspect that in model Meta section you have set model ordered by an 'external' field (related model 'station__departure_time'
). When you write query django make joins to this 'external' field for sorting purposes.
In this case you should use distinct()
method or clear ordering using .order_by()
Upvotes: 1