避免存在错误

时间:2017-07-25 15:09:18

标签: django

def clean_bank_account(self):
    import ipdb; ipdb.set_trace()
    ssn = self.form.cleaned_data.get('ssn')
    customer = CustomerProfile.objects.filter(ssn=ssn)

    bank_account = self.form.cleaned_data.get('bank_account')
    bank = self.form.cleaned_data.get('bank')
    bank_transit = self.form.cleaned_data.get('bank_transit')
    qs = FinancialProfile.objects.filter(
        bank=bank,
        bank_transit=bank_transit,
        bank_account=bank_account)

    if customer.count() == 1:
        for cust in customer:
            qs = qs.exclude(customer_id=cust.id)
    if qs.count() > 0:
        # The concatenation of bank transit, the bank account and the bank
        # number must be unique. Hence, the following message would be
        # displayed if it is already in use.
        raise ValidationError(
            _('The bank, the bank transit and the bank are already in use.')
        )

    if bank not in (None, ''):
            # Check bank account format for specific banks
            length = settings.LOANWOLF_BANK_ACCOUNTS_LENGTH.get(bank)
            if length:
                if bank_transit not in (None, ''):
                    if not bank_account.isnumeric() or length != len(bank_account):
                        raise ValidationError(
                            _('Bank account number must contain %d digits') % length  # noqa
                        )
                else:
                    raise ValidationError(
                        _('Cannot validate bank account without a valid bank transit')  # noqa
                    )
    return bank_account

我想改进这段代码的结构。我不能CustomerProfile.objects.get(ssn=ssn),因为如果对象不存在,它会给我一个错误。相反,我决定使用过滤器创建一个列表,该列表返回一个查询集。用线

if customer.count() == 1:
        for cust in customer:
            qs = qs.exclude(customer_id=cust.id)
如果列表中只有一个客户,

将排除客户ID。一开始,我认为我可以删除for循环并只使用客户,但我不能,因为它是一个查询集。我认为我能做到有没有办法改进这部分代码?

1 个答案:

答案 0 :(得分:0)

循环可以由in过滤器

替换
 qs = qs.exclude(customer_id__in=[cust.id for cust in customer])