多对多“通过代理” Django 中的关系
我的数据模型由三个主要实体组成:
class User(models.Model):
...
class Source(models.Model):
user = models.ForeignKey(User, related_name='iuser')
country = models.ForeignKey(Country, on_delete=models.DO_NOTHING)
description = models.CharField(max_length=100)
class Destination(models.Model):
user = models.ForeignKey(User, related_name='wuser')
country = models.ForeignKey(Country)
我正在尝试创建一个查询集,该查询集按用户(多对多)将所有源与目的地连接起来。通过这种方式,我将拥有一个包含每个用户所有可能的源/目标组合的表。 在 SQL 中,我将简单地连接三个表并从每个表中选择适当的信息。
我的问题是如何执行查询?如何访问查询数据?
My data model consists of three main entities:
class User(models.Model):
...
class Source(models.Model):
user = models.ForeignKey(User, related_name='iuser')
country = models.ForeignKey(Country, on_delete=models.DO_NOTHING)
description = models.CharField(max_length=100)
class Destination(models.Model):
user = models.ForeignKey(User, related_name='wuser')
country = models.ForeignKey(Country)
I am trying to create a queryset which is join all sources with destinations by user (many to many). In such a way I would have a table with all possible source/destination combinations for every user.
In SQL I would simple JOIN the three tables and select the appropriate information from each table.
My question is how to perform the query? How to access the query data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 django 中,查询是在模型对象上完成的,它有很好的记录。查询或查询集是惰性的,当它们执行时,它们通常返回一个字典列表,列表中的每个字典都包含
字段
,后跟值
,例如:[ {'user':'albert','country':'美国和澳大利亚:)','description':'我的描述'},....]
。每个用户的所有可能的源、目标组合?
我认为你必须使用 反向关系Ship 来完成此操作,例如:
请注意,我使用的是具有
ForeignKey
的模型Source
和Destination
的较小大小写名称> 与的关系用户
这将加入所有三个选项卡浏览其丰富的文档。编辑:
要进行内部联接,您必须告诉查询,这可以通过在反向模型名称上使用
__isnull=False
来简单地实现:这应该执行内部联接加入所有表。
然后,您可以像之前一样使用
values
选择要显示的内容。希望有帮助。 :)
In django queries are done on the model object, its well documented. The queries or querysets are lazy and when they execute they generally return a list of dict, each dict in the list contains the
field
followed by thevalue
eg:[{'user':'albert','country':'US and A :) ','description':'my description'},....]
.All possible source,destination combinations for every user?
I think you will have to use a reverse relation ship to get this done eg:
notice that i'm using the smaller case name of the models
Source
andDestination
which haveForeignKey
relationship withUser
this will join all the three tabels go through the documentation its rich.Edit:
To make an inner join you will have to tell the query, this can be simply achieved by using
__isnull=False
on the reverse model name:This should do a inner join on all the tables.
Then you can select what you want to display by using
values
as earlier.hope that helps. :)