我正试图将下面的visible
函数中的两个计数查询合并为一个查询。 函数应该返回True,如果没有关系或者有关系并且某些特定的过滤是真的。仅当关系存在于一个查询中时才在ManyToManyField上过滤
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
编辑:更多的代码和注释,替换次数与存在。
m2m关系用于日期限制,但如果没有日期限制可用,则函数应该返回True(如果没有限制,对象可见,但如果限制存在但不匹配当前日期则不可见)。
示例代码只是一个简化示例,我需要这样做并实际返回querysets。
什么问题呢?任何错误? –
不,我只是想避免做两个分贝查询 – sunn0