我正在寻找一种策略来验证四种模型的密钥的唯一性,这四种模型之间具有相互关系,然后才能将它们保存在数据库中。
换句话说,我想检查密钥的唯一性,以便在使用Model.save()
方法时数据库中不存在不一致,并且只在所有唯一密钥真正唯一时才使用它。 / p>
以下视图为例,LegalPerson
,{{分别为 cnpj ,地址和数字字段1}}和Email
必须是唯一的。
Phone
我一直在研究,发现django中的模型有一些验证方法,如class StoreRegistrationView(View):
'''
Classe responsavel pelo cadastro de lojas
'''
def post(self, request):
if request.method == 'POST':
#import pdb; pdb.set_trace()
form = StoreForm(request.POST)
if form.is_valid():
lp = LegalPerson(
cnpj = form.cleaned_data['cnpj'],
corporate_name = form.cleaned_data['corporate_name'],
fantasy_name = form.cleaned_data['fantasy_name'],
state_inscription = form.cleaned_data['state_inscription'],
municipal_inscription = form.cleaned_data['municipal_inscription'],
)
lp.save()
address = Address(
street = form.cleaned_data['street'],
neighborhood = form.cleaned_data['neighborhood'],
number = form.cleaned_data['number'],
complement = form.cleaned_data['complement'],
city = form.cleaned_data['city'],
estate = form.cleaned_data['estate'],
country = 'Brasil',
cep = form.cleaned_data['cep'],
latitude = form.cleaned_data['latitude'],
longitude = form.cleaned_data['longitude'],
person = lp,
)
address.save()
email = Email(
address = form.cleaned_data['email'],
person=lp,
)
email.save()
phone = Phone(
number=form.cleaned_data['phone_number'],
person=lp,
)
phone.save()
# Mensagem de sucesso que será disponibilizada para o usuário
messages.success(request, 'Cadastro de loja efetuado com sucesso.')
return redirect('importar-produtos')
messages.warning(request, 'Erro durante o cadastro.')
context = {
'store_form': StoreForm(),
}
return render(request, 'n3oadmin/store-registration.html', context)
,Model.full_clean()
和Model.clean()
。
答案 0 :(得分:1)
您应该创建多个模型表单,而不是使用常规表单。
class LegalPersonForm(forms.ModelForm):
class Meta:
model = LegalPerson
fields = [...]
class = AddressForm(forms.ModelForm):
class Meta:
model = LegalPerson
exclude = ['person']
然后,在视图和模板中使用模型表单。模型表单将负责验证唯一约束。
if request.method == 'POST':
address_form = AddressForm(request.POST)
legal_person_form = LegalPersonForm(request.POST)
if address_form.is_valid() and legal_person_form.is_valid():
person = legal_person_form.save()
address = address_form.save(commit=False)
address.person = person
address.save()
...
return redirect('importar-produtos')
else:
address_form = AddressForm()
legal_person_form = LegalPersonForm()
context = {
'address_form': address_form,
'legal_person_form': legal_person_form,
}
return render(request, 'n3oadmin/store-registration.html', context)
请注意,您可以在模型表单中排除外键字段。然后,在视图中,您可以使用commit=False
保存,设置外键,然后保存实例。
另请注意,我们仅在AddressForm()
块中实例化了空白表单LegalPersonForm
和else
(对于GET请求)。这意味着如果表单有效,您可以在模板中看到表单错误,而不是空白表单。
答案 1 :(得分:0)
您可以在此处参考此处设置唯一字段。
https://docs.djangoproject.com/en/1.11/ref/models/fields/#unique