使用外键以表单的干净方法访问其他对象Django

时间:2018-06-20 12:27:52

标签: python django django-models django-forms

我要访问外键的其他对象。

models.py

from django.db import models

class Box(models.Model):
    name = models.CharField(max_length=200,null=True)
    apples= models.IntegerField(blank=True, null=True)
    banana = models.IntegerField(blank=True, null=True)
    mango = models.IntegerField(blank=True, null=True)
    def __str__(self):
        return self.name

class Buyer(models.Model):
    name_of_buyer = models.CharField(max_length=200,null=True)
    address_of_buyer = models.CharField(max_length=200,null=True)
    interested_in = models.ForeignKey(Box,on_delete=models.CASCADE,null=True)
    Pickup_dt = models.DateField(null=True)
    Pickup_time = models.CharField(max_length=80,null=True) 

forms.py

from .models import Price

class Sale(forms.ModelForm):
    def clean_interested_in(self):
        buyer_interested_in_box = self.cleaned_data['interested_in']
        # if the selected box contains less than 10 apples, 10 bananas and 10 mangos:
               raise forms.ValidationError('Not enough fruits.Please select another box')         
    class Meta:
        model = Buyer
        widgets = {
            'Pickup_dt': forms.DateInput(attrs={'class':'datepicker'}),
            'Pickup_time': forms.DateInput(attrs={'class':'timepicker'}),
        }
        fields = '__all__'

如何使用外键ID验证此表单?

1 个答案:

答案 0 :(得分:2)

您可以使用clean_interested_in方法。在该方法中,self.cleaned_data['interested_in']应该是相关对象。

def clean_interested_in(self):
    buyer_interested_in_box = self.cleaned_data['interested_in']
    if ((buyer_interested_in_box.apples is None or buyer_interested_in_box.apples < 10) or 
            (buyer_interested_in_box.bananas is None or buyer_interested_in_box.bananas < 10) or
            (buyer_interested_in_box. mangos is None or buyer_interested_in_box. mangos < 10)):
       raise forms.ValidationError('Not enough fruits. Please select another box')
    return buyer_interested_in_box

请注意,您需要检查水果值是否为None。如果将模型字段更改为null=False,则不需要此检查,并且可以简化代码。