Getting Unique Foreign Keys in Django?
Supp开发者_如何学Cose 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
?
http://docs.djangoproject.com/en/dev/ref/models/querysets/#in
Farm.objects.filter(tree__in=TreeQuerySet)
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 ])
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.
精彩评论