Django:filter()或get()

时间:2018-11-14 16:08:30

标签: 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

2 个答案:

答案 0 :(得分:2)

您可以在此处保存查询。查询集上的.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检查中进行此操作)。即便如此,您仍然需要大量数据才能看到实际的性能提升。

答案 1 :(得分:1)

我会这样写代码:

def clean_code(self):
    input_code = self.cleaned_data['code']

    try:
        discount_code = self.event.discounts.get(code=input_code)
    except Discount.DoesNotExist:  # suppose your model is named Discount
        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