Oli
Oli

Reputation: 239998

Get distinct objects for foreign key in existing Django query

Consider the following many-to-one relationship. Users can own many widgets:

class Widget(models.Model):
    owner = models.ForeignKey('User')

class User(models.Model):
    pass

I have a fairly complicated query that returns me a queryset of Widgets. From that I want to list the distinct values of User.

I know I could loop my Widgets and pull out users with .values('owner') or {% regroup ... %} but the dataset is huge and I'd like to do this at the database so it actually returns Users not Widgets first time around.

My best idea to date is pulling out a .values_list('owner', flat=True) and then doing a User.objects.filter(pk__in=...) using that. That pulls it back to two queries but that still seems like more than it should need to be.

Any ideas?

Upvotes: 4

Views: 3520

Answers (1)

catavaran
catavaran

Reputation: 45595

Use backward relationship:

User.objects.distinct().filter(widget__in=your_widget_queryset)

Upvotes: 6

Related Questions