Django 查询在哪里
如何使用 django 对象查询来做到这一点:
SELECT * FROM test WHERE (test_id IN (SELECT test_id FROM test_subject_set)) AND (test_begin_time < '') AND (test_end_time > '')
模型:
class Test(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User)
groups = models.ManyToManyField(Group)
class TestSubjectSet(models.Model):
id = models.AutoField(primary_key=True)
test = models.ForeignKey(Test)
How to do this using django object query:
SELECT * FROM test WHERE (test_id IN (SELECT test_id FROM test_subject_set)) AND (test_begin_time < '') AND (test_end_time > '')
The model:
class Test(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User)
groups = models.ManyToManyField(Group)
class TestSubjectSet(models.Model):
id = models.AutoField(primary_key=True)
test = models.ForeignKey(Test)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两个查询集是记录执行此操作的方法。无论如何,这将是一个数据库命中。
Two querysets are documented way of doing this. It will be one database hit anyway.
泰莎博士差一点就明白了。
Tyrsa 执行此操作的方式不会为您提供 TestSubjectSet 中的测试 ID 列表,而是为您提供 TestSubjectSet 查询集。
另外,我对 test_begin_time 和 test_end_time 字段感到困惑,因为您没有在模型中提及它们。
更新:在查询集上使用 list() ,因为根据 DrTyrsa 发布的链接,数据库“不能很好地优化嵌套查询集”。
DrTyrsa just about had it.
The way Tyrsa was doing it would not give you a list of the Test ids from TestSubjectSet, but instead give you a TestSubjectSet queryset.
Also, I was confused by the test_begin_time and test_end_time fields, because you didn't mention them in your models.
Update: Used list() on the queryset, because, according to the link DrTyrsa posted, DBs "don't optimize nested querysets very well".
这对我有用:
this worked for me: