Django 一种更有效的方法来检查是否存在具有特定值的相关项
在我的一个模型类中有以下方法。它的设计目的是让我的视图知道日志可以编辑。如果条目不超过90天,并且没有任何在LineItems reconciled_date字段中具有值的相关LineItems,则应返回true。Ie所有相关行项目的对账日期字段必须为空 该方法可以工作,但它通过行项进行迭代,这似乎非常低效。有更好的办法吗 Models.pyDjango 一种更有效的方法来检查是否存在具有特定值的相关项,django,django-models,Django,Django Models,在我的一个模型类中有以下方法。它的设计目的是让我的视图知道日志可以编辑。如果条目不超过90天,并且没有任何在LineItems reconciled_date字段中具有值的相关LineItems,则应返回true。Ie所有相关行项目的对账日期字段必须为空 该方法可以工作,但它通过行项进行迭代,这似乎非常低效。有更好的办法吗 Models.py class JournalEntry(models.Model): user = models.ForeignKey(settings.AUTH_
class JournalEntry(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False, blank=False)
date = models.DateField(null=False, blank=False)
def can_edit(self):
"""Checks if logged user can edit"""
is_reconciled = 0
for lineitem in self.lineitem_set.all():
if lineitem.reconciliation_date != None:
is_reconciled = 1
if (datetime.date.today() < (self.date + datetime.timedelta(90))) and is_reconciled == 0:
return True
else:
return False
谢谢您可以执行单个查询,以确定日记账是否有任何具有非空对账日期的相关行项目。如果您想在其他方法中重复使用它,那么将其放在属性中可能会很方便
@property
def is_reconciled(self):
"""Returns True if any related line items have a non-null reconciliation_date"""
return self.lineitem_set.filter(reconciliation_date__isnull=False).exists()
然后你可以在你的方法中使用这个
def can_edit(self):
"""Checks if logged user can edit"""
# First check if the entry is less than 90 days old as it does not require
# a call to the DB
if self.date > datetime.date.today() - datetime.timedelta(days=90):
# If the entry is less than 90 days old then we return the inverse of is_reconciled
return not self.is_reconciled
return False
目前还不清楚lineitem_集是什么;你也应该发布这个模型。此外,您是否真的遇到了性能问题,或者只是在理论上?一切都可以优化,但只有当性能成为实际问题时,才最好担心性能。您能分享行项目模型吗?