python - Django:过滤器()或获取()
问题描述
我写discount_code.first().is_active()
的方式是正确的,还是最好使用.get
(折扣)代码是每个事件的代码唯一字段?不同的事件可以有代码。
def clean_code(self):
input_code = self.cleaned_data['code']
# Check if discount code exists
discount_code = self.event.discounts.filter(code=input_code)
discount_code_exists = discount_code.exists()
if not discount_code_exists:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
else:
if not discount_code.first().is_active():
raise forms.ValidationError(_("This discount code is not available\
anymore."),
code='code_not_active')
return input_code
解决方案
您可以在此处保存查询。查询集的返回值包含.first()
验证所需的所有信息:
def clean_code(self):
input_code = self.cleaned_data['code']
# this is None if it doesn't exist
discount_code = self.event.discounts.filter(code=input_code).first()
if not discount_code:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
exists()
仅当您不需要进一步处理查询集(您在is_active
检查中执行此操作)时,使用才有益。即便如此,您也需要大量数据才能看到真正的性能提升。
推荐阅读
- web-scraping - F# 中的网络爬取
- vb.net - 检测 DataGridView 单元格中的符号
- arrays - React Complex Array,如何提取值?
- python-3.x - 安装 TensorFlow | 蜘蛛 | Python 3.7 Win64
- android - XML 样式完全没有效果?
- python - 带有 UUID 的 Flask-WTF 选择字段
- hyperledger-fabric - Go 供应商许可证
- python - 应用,lambda 函数问题
- sql-server - 如何从 C# 中的数据库中获取最后一个 id
- python - SQLAlchemy:使用变量表名