I have a basic FK to user, call it owner
class Baz(models.Model):
owner = models.ForeignKeyField(User)
....
....
Now, with a queryset of Baz's, is there something that I can chain that will give me only one Baz per owner?
The function you are truly looking for is GROUP BY. However, Django does not typically support building querysets that do not directly output model instances. In this situation, you have two approachs:
Baz.objects.values('owner').distinct()
This will net you each distinct owner, but not the Baz object itself.
Baz.objects.filter(pk__in=Baz.objects.values('owner').distinct())
The above will perform a subquery (at least in MySQL) and should give the intended results, but isn't the most efficient way to retrieve it.
Lastly, since aggregates have been added, it may be possible for you to write a custom aggregate class which would work as a kind of "Distinct" and simply "GROUP BY ".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With