magneticMonster
magneticMonster

Reputation: 2423

Getting Unique Foreign Keys in Django?

Suppose my model looks like this:

class Farm(models.Model):
   name = ...

class Tree(models.Model):
   farm = models.ForeignKey(Farm)

...and I get a QuerySet of Tree objects. How do I determine what farms are represented in that QuerySet?

Upvotes: 4

Views: 2021

Answers (3)

gerdemb
gerdemb

Reputation: 11487

http://docs.djangoproject.com/en/dev/ref/models/querysets/#in

Farm.objects.filter(tree__in=TreeQuerySet)

Upvotes: 6

Evgeny
Evgeny

Reputation: 10896

Here is a way to have the database do the work for you:

farms = qs.values_list('farm', flat=True).distinct() 
#values_list() is new in Django 1.0

return value should evaluate to something like:

(<Farm instance 1>, <Farm instance5>)

were farms will be those that have trees in that particular query set.

For all farms that have trees, use qs = Tree.objects

Keep in mind that if you add order_by('some_other_column') then distinct will apply to the distinct combinations of 'farm' and 'some_other_column', because other column will also be in the sql query for ordering. I think it's a limitation (not an intended feature) in the api, it's described in the documentation.

Upvotes: 0

Skylar Saveland
Skylar Saveland

Reputation: 11464

There might be a better way to do it with the Django ORM and keep it lazy but you can get what you want with regular python (off the top of my head):

>>> set([ t.farm for t in qs ])

Upvotes: 4

Related Questions