Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-queryset get one object per field=foo

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?

like image 728
Skylar Saveland Avatar asked Apr 07 '26 09:04

Skylar Saveland


1 Answers

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 ".

like image 97
David Cramer Avatar answered Apr 09 '26 22:04

David Cramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!