首页 > 解决方案 > 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

标签: pythondjango

解决方案


您可以在此处保存查询。查询集的返回值包含.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检查中执行此操作)时,使用才有益。即便如此,您也需要大量数据才能看到真正的性能提升。


推荐阅读