DJANGO模型内部加入ORM问题



假设我有以下三个模型,请参见以下三个模型:我想构造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模型的批准。

类似的东西?

Approve.objects.filter(process__processstep_set__order=<value>)

现在,我只能使用RAW 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

如果你们有更好的解决方案,我想听听您的来信,谢谢〜

最新更新