django - 一种更有效的方法来检查没有具有特定价值的相关项目
问题描述
我的模型类之一中有以下方法。它旨在让我的观点知道可以编辑 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
谢谢
解决方案
您可以执行单个查询来确定是否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
推荐阅读
- python - 有没有办法获得可以使用 Azure Python SDK 或 API 在你的 Azure 帐户上创建的最大虚拟机数量?
- java - Android 时间选择器对话框更改首先显示的时间
- excel - 使用 vlookup 函数返回最大值
- amazon-web-services - 如何从 AWS Lambda 函数中扫描 dynamodb 表
- python - pytorch:计算向量函数的向量-雅可比积
- magento - 添加帐单和送货地址以注册表格 Magento 2
- julia - Julia:`import` 和 `using` 的用例
- r - 无法通过 rmarkdown 编织 html
- javascript - 重定向后获取网址
- html - 使用 reactjs 更改主 index.html 上的语言