简体   繁体   English

在Django中获取唯一的外键?

[英]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. ...我得到一个Tree对象的QuerySet How do I determine what farms are represented in that QuerySet ? 如何确定QuerySet中表示的服务器场?

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

Farm.objects.filter(tree__in=TreeQuerySet)

使用Django ORM可能有更好的方法来保持懒惰,但你可以通过常规python得到你想要的东西(在我的头顶):

>>> 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 对于所有拥有树的农场,请使用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. 请记住,如果添加order_by('some_other_column')则distinct将应用于'farm'和'some_other_column'的不同组合,因为其他列也将在sql查询中进行排序。 I think it's a limitation (not an intended feature) in the api, it's described in the documentation . 我认为它是api中的限制(不是预期的功能),它在文档中有描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM