问题描述
我大概有这样的模型:
class ModelA(models.Model):
field = models.CharField(..)
class ModelB(models.Model):
name = models.CharField(.., unique=True)
modela = models.ForeignKey(ModelA, blank=True, related_name='modelbs')
class Meta:
unique_together = ('name','modela')
我想做一个查询,内容如下:获取所有ModelA,其中字段名称等于X,其中ModelB模型的名称为X或根本没有模型名称"
I want to do a query that says something like: "Get all the ModelA's where field name equals to X that have a ModelB model with a name of X OR with no model name at all"
到目前为止,我有这个:
So far I have this:
ModelA.objects.exclude(field=condition).filter(modelsbs__name=condition)
这将为我提供至少具有一个modelB的所有ModelA(实际上,它始终只是一个)-但是,如果ModelA没有相关的ModelB,则它将不在结果集中.我需要它放在结果集中,像obj.modelb = None
This will get me all the ModelAs that have at least one modelB (and in reality it will ALWAYS be just one) - but if a ModelA has no related ModelBs, it will not be in the result set. I need it to be in the resultset with something like obj.modelb = None
我该怎么做?
推荐答案
使用Q组合两个条件:
from django.db.models import Q
qs = ModelA.objects.exclude(field=condition)
qs = qs.filter(Q(modelbs__name=condition) | Q(modelbs__isnull=True))
要检查生成的SQL查询:
To examine the resulting SQL query:
print qs.query.as_sql()
在类似的查询上,这将生成一个LEFT OUTER JOIN ... WHERE(a.val = b或a.id IS NULL).
On a similar query, this generates a LEFT OUTER JOIN ... WHERE (a.val = b OR a.id IS NULL).
这篇关于Django左加入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!