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 to determine which farms are represented in this QuerySet ?

+4
source share
3 answers

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

 Farm.objects.filter(tree__in=TreeQuerySet) 
+6
source

There might be a better way to do this with Django's ORM and keep it lazy, but you can get what you want using regular python (from the head):

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

Here's how to make a database for you:

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

the return value should be evaluated something like this:

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

there were farms that will have trees in this particular query.

For all farms with trees, use qs = Tree.objects

Keep in mind that if you add order_by('some_other_column') , the different ones will apply to individual combinations of "farm" and "some_other_column", because another column will also be in the sql query for the order. I think this is a limitation (not an intended function) in the api, it is described in the documentation .

0
source

All Articles