假设我有以下三个模型,请参见:我想构建一个Django模型查询,以存档与以下SQL语句相同的效果。
SQL语句
select B.value, C.special
from B inner join C
where B.version = C.version and B.order = C.order;
我有以下三个模型:
class Process(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=150)
class ProcessStep(models.Model):
process = models.ForeignKey(Process)
name = models.CharField(max_length=30)
...
order = models.SmallIntegerField(default=1)
version = models.SmallIntegerField(null=True)
class Approve(models.Model):
process = models.ForeignKey(Process)
content = models.CharField(max_length=300)
...
version = models.SmallIntegerField(null=True)
order = models.SmallIntegerField(default=0)
我想找到所有与ProcessStep模型具有相同(版本,顺序)元组匹配的Approves。
答案 0 :(得分:0)
这样的东西?
Approve.objects.filter(process__processstep_set__order=<value>)
答案 1 :(得分:0)
现在我只能通过使用原始SQL来提出解决方案,请参阅以下代码。
from django.db import connection
cursor = connection.cursor()
cursor.execute("
SELECT A.id, B.id
from approval_approve as A inner join approval_approvalstep as B
where A.process_id = B.process.id
and A.order = B.order
and A.version = B.version;")
# do something with the returned data
如果你们有更好的解决方案,我想听听你的意见,谢谢〜