【发布时间】:2021-10-19 18:55:40
【问题描述】:
给定模型的某些字段不直接映射到ModelForm 的字段,我应该在哪里设置它们的值?在下文中,form.blast_db 应分配给model.protein_db 或model.nucleotide_db,具体取决于它是什么类型的爆炸数据库。它们是互斥的,但是是必需的,所以必须在调用model.full_clean() 之前设置它们。
from django.db import models
class BlastQuery(models.Model):
# Protein/nucleotide blast DB. Mutually exclusive, one must be provided
protein_db = models.ForeignKey(ProteinDB, null=True, blank=True)
nucleotide_db = models.ForeignKey(ProteinDB, null=True, blank=True)
# Just 1 field to keep it terse but in reality there are many other fields
foo = models.IntegerField()
def clean(self):
if self.protein_db and self.nucleotide_db:
raise ValidationError('Protein/nucleotide DB are mutually exclusive')
if not self.protein_db and not self.nucleotide_db:
raise ValidationError('Protein/nucleotide DB are required')
from django import forms
class BlastForm(forms.ModelForm):
# Magical field that's like a ModelChoiceField but can
# hold both ProteinDB and NucleotideDB instances
blast_db = BlastDBField()
class Meta:
model = BlastQuery
fields = ('foo',)
【问题讨论】:
标签: django django-forms modelform