仅当一个查询中存在关系时才过滤ManyToManyField
我试图将下面的 visible
函数中的两个计数查询合并为一个查询 . 如果没有关系或者存在关系且某些特定过滤为真,则函数应返回True .
class OtherModel(models.Model):
starts = models.DateField()
ends = models.DateField()
class MyModel(models.Model):
m2m = models.ManyToManyField('OtherModel', blank=True, )
def visible(self):
# Should always return True if no relations to OtherModel are present.
if self.m2m.exists():
# If relations to OtherModel are present check for starts and ends.
# The reason for the first check is that if there are no relations
# and the below query returns 0 the function will return False
today = datetime.date.today()
return self.m2m.filter(starts__lte=today, ends__gte=today).exists()
return True
EDIT :更多代码和注释,替换为存在的计数 .
m2m关系用于日期限制,但如果没有可用的日期限制,则该函数应返回True(如果没有任何限制则对象可见,但如果存在限制但不匹配当前日期则不可见) .
示例代码只是一个简化示例,我将需要执行此操作并实际返回查询集 .
回答(2)
不确定你的实际要求是什么,但我认为你想避免 self.m2m.count() > 0
额外检查并想从函数返回一个布尔值,如果它存在与否,那么你需要.exists如果QuerySet包含任何结果将返回 True
,并且 False
如果不:
def visible(self):
# return True or False
return self.m2m.filter(some_filter=some_value).exists()
2 years ago
用Q和聚合解决了它,感谢Aamir for exists():