django createviw-创建另一个模型对象并在当前模型中使用它

时间:2018-03-03 13:22:06

标签: django activity-oncreateview

我有两个模型,如下所示。

class Account(models.Model):

   ASSET='A'
   LIABILITY='L'
   INCOME='I'
   EXPENSE='E'
   ACCOUNT_TYPE=((ASSET,'Asset'),
        (LIABILITY,'Liability'),
        (INCOME,'Income'),
        (EXPENSE,'Expense'))
   name=models.CharField(unique=True,db_index=True,max_length=70)
   type=models.CharField(choices=ACCOUNT_TYPE,max_length=1)
class Person(models.Model):
    first_name=models.CharField(max_length=30,)
    last_name=models.CharField(max_length=30,)
    account=models.OneToOneField(Account,on_delete=models.CASCADE)

Person模型具有以下CreateView和模型表单。

class CreatePerson(CreateView):
    model=Person
    form_class=CreatePersonForm
class CreatePersonForm(forms.ModelForm):
    display_name=forms.CharField()

    class Meta:
        model= Person
        fields = ['first_name','last_name','display_name']

创建新的 Person 时,我需要

  1. 首先创建一个帐户对象(名称= display_name,类型=' A')并需要将其分配给 Person 对象

  2. 如果具有相同display_name的帐户已存在,则会再次呈现该表单,并显示验证错误。

  3. 有人可以指出正确的方向继续吗?

    感谢。

1 个答案:

答案 0 :(得分:1)

您可以实施clean_display_name方法来检查Acount是否已存在:

class CreatePersonForm(forms.ModelForm):
    display_name=forms.CharField()

    class Meta:
        model= Person
        fields = ['first_name','last_name','display_name']

    def clean_display_name(self):
        name = self.cleaned_data.get('display_name')
        account = Account.objects.filter(name=name).exists() 
        if account:
            raise forms.ValidationError('Account already exists')
        return name

要向个人资料添加帐户,您可以覆盖视图的form_valid方法:

class CreatePerson(CreateView):
    model=Person
    form_class=CreatePersonForm

    def form_valid(self, form):
        account = Account.objects.create(name=form.cleaned_data['display_name'])
        form.instance.account = account
        return super().form_valid(form)