Ordering by related field creates duplicates in resultant querysets
|Reported by:||Mathijs de Bruin||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.4|
|Severity:||Normal||Keywords:||ordering, duplicates, related|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
When specifying an
ordering property in a Model's Meta class, based on a field in a model with a ForeignKey relation to this model, duplicate objects are returned in the resulting queryset.
A test application with failing unittest is attached to the report in a tarball. In summary, the following models and query code can be used to replicate this issue:
class TestModel(models.Model): class Meta: ordering = ('testrelated__field', ) class TestRelated(models.Model): field = models.IntegerField() testmodel = models.ForeignKey(TestModel)
Now the following behaviour can be observed:
>>> o = TestModel() >>> o.save() >>> r1 = TestRelated(field=1, testmodel=o) >>> r2 = TestRelated(field=2, testmodel=o) >>> r1.save() >>> r2.save() >>> TestModel.objects.all() [<TestModel: 1>, <TestModel: 1>]
The behaviour has found to exist for the SQLite backend and might or might not occur with other database backends.