Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 392
magneticMonster Avatar asked Dec 30 '22 09:12

magneticMonster


2 Answers

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

Farm.objects.filter(tree__in=TreeQuerySet)
like image 53
gerdemb Avatar answered Dec 31 '22 21:12

gerdemb


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 ])
like image 26
Skylar Saveland Avatar answered Dec 31 '22 23:12

Skylar Saveland