是否可以将下面的sql转换为django orm调用,还是必须使用原始sql?
感谢您的帮助
我的模特:
class Parent(models.Model):
slug = models.SlugField()
class Child(models.Model):
slug = models.SlugField()
parent = models.ForeignKey('Parent')
value = models.CharField(max_length=128)
我的sql:
select *
from parent as p
left join child as c on p.id = c.parent_id and c.slug in ('s0','s1','s2')
where p.id not in (select p.id
from parent as p
inner join child as c on p.id = c.parent_id and c.slug = 's3' and c.value = 'v3')
order by p.slug
答案 0 :(得分:0)
Parent.objects.filter(child__slug__in=['s0','s1','s2']).exclude(child__slug='s3', child__value='v3').order_by('slug')
虽然排除child.slug =='s3'的位置,但是当它不在__in
数组中时,不应该首先包含在内。
<强>更新强>
要包含没有孩子的父母,请在过滤器中使用Q
个对象:
from django.db.models import Q
Parent.objects.filter(Q(child__isnull=True) | Q(child__slug__in=['s0','s1','s2']))