Django - 间接连接查询
如何返回一个间接连接查询,该查询为我提供问题模型中的所有问题。需要注意的是,对于每个问题,我都需要能够访问 UserData 模型。间接关系是 Question -> User 和 User <- UserData (如果可能的话,我不希望更改模型结构)。
class Question(models.Model):
description = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
image_url = models.CharField(max_length=200)
user = models.ForeignKey(User)
class Answer(models.Model):
question = models.ForeignKey(Question)
text = models.CharField(max_length=16000)
user = models.ForeignKey(User)
class UserData(models.Model):
user = models.OneToOneField(User)
access_token = models.CharField(max_length=32)
profile_image_url = models.CharField(max_length=200)
编辑:我认为这种关系被认为是“反向关系”。
How can I return an indirect joined query that gives me all of the Questions in the Question model. The caveat, is that for each question, I need to be able to access the UserData model. The indirect relationship is Question -> User and User <- UserData (I prefer not to change the model structure if possible).
class Question(models.Model):
description = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
image_url = models.CharField(max_length=200)
user = models.ForeignKey(User)
class Answer(models.Model):
question = models.ForeignKey(Question)
text = models.CharField(max_length=16000)
user = models.ForeignKey(User)
class UserData(models.Model):
user = models.OneToOneField(User)
access_token = models.CharField(max_length=32)
profile_image_url = models.CharField(max_length=200)
Edit: I think this relationship is considered a "reverse relationship".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将为每个问题获取
User
对象和UserData
对象。不支持反向关系除非在OneToOne
关系中,就像您所拥有的 (如此处所示)will get both the
User
object and theUserData
object for every question. Reverse relationships aren't supported except inOneToOne
relationships like you have (As seen here)考虑select_lated()。
从 3 个查询,到仅使用 select_lated() 的 2 个查询,再到使用 select_lated() 给出更好参数的 1 个查询。
有趣的是,您不必调用与
('user', 'user__userdata')
相关的 select:您可以看到最后一个查询仅使用 '从 3 个表中获取数据>user__userdata
':Consider select_related().
From 3 queries, to 2 queries with just select_related(), to 1 query with select_related() given better arguments.
It is interresting to note that you don't have to call selected related with
('user', 'user__userdata')
: You can see the last query fetches data from the 3 tables with just 'user__userdata
':