首页 > 解决方案 > 一种更有效的方法来检查没有具有特定价值的相关项目

问题描述

我的模型类之一中有以下方法。它旨在让我的观点知道可以编辑 JournalEntry。如果条目不超过 90 天并且没有任何相关 LineItems 在 LineItems reconciled_date 字段中具有值,则它应该返回 true。即所有相关的 LineItems 在其 reconciled_date 字段中必须有 NULL。

该方法有效,但它通过 LineItems 进行迭代,这似乎非常低效。有没有更好的办法?

模型.py

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

谢谢

标签: djangodjango-models

解决方案


您可以执行单个查询来确定是否JournalEntry有任何相关行项目具有非空的对帐日期。如果您想在其他方法中重用它,将它放在属性中可能会很方便

@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

推荐阅读