在使用Django框架开发应用程序时,遇到一个多对多关系的错误:“需要为字段“…”提供值,才能使用这个多对多关系”。造成错误的原因是,在保存数据时,Django无法找到相关模型中的外键字段的值。
2、解决方案
解决方案有两种:
1. 使用 ModelForm
使用ModelForm可以自动生成表单,并且在保存数据时,会自动处理外键字段的值。具体步骤如下:
- 在models.py中定义模型:
class SurveyResult(models.Model):
stay = models.OneToOneField(Stay, related_name='survey')
created = models.DateTimeField(default=datetime.now)
vote = models.BooleanField(default=False)
vote_service = models.BooleanField(default=False)
comment = models.TextField(blank=True, null=True)
def getThreads(self):
return SurveyThread.objects.filter(parent_survey = self)
threads = property(getThreads)
def __unicode__(self):
return self.vote and 'Good' or 'Bad'
class Meta:
get_latest_by = '-created'
class SurveyThread(models.Model):
survey = models.ManyToManyField(SurveyResult, related_name='parent_survey')
email = models.EmailField(max_length=200)
comment = models.TextField(blank=True, null=True)
- 在forms.py中定义表单:
from django.forms import ModelForm
class SurveyThreadForm(ModelForm):
class Meta:
model = SurveyThread
fields = ['email', 'comment']
- 在views.py中使用表单:
def survey_view(request):
survey_list = SurveyResult.objects.filter(stay__guest__user=request.user) \
.select_related('stay', 'stay__guest')
forms = {}
for survey in survey_list:
forms[survey] = SurveyThreadForm(data=request.POST or None, survey=survey)
if forms[survey].is_valid():
instance = forms[survey].save()
return redirect('.')
2. 手动设置外键字段的值
如果不想使用ModelForm,也可以手动设置外键字段的值。具体步骤如下:
- 在models.py中定义模型:
class SurveyResult(models.Model):
stay = models.OneToOneField(Stay, related_name='survey')
created = models.DateTimeField(default=datetime.now)
vote = models.BooleanField(default=False)
vote_service = models.BooleanField(default=False)
comment = models.TextField(blank=True, null=True)
def getThreads(self):
return SurveyThread.objects.filter(parent_survey = self)
threads = property(getThreads)
def __unicode__(self):
return self.vote and 'Good' or 'Bad'
class Meta:
get_latest_by = '-created'
class SurveyThread(models.Model):
survey = models.ManyToManyField(SurveyResult, related_name='parent_survey', blank=True, null=True)
email = models.EmailField(max_length=200)
comment = models.TextField(blank=True, null=True)
- 在views.py中手动设置外键字段的值:
def survey_view(request):
survey_list = SurveyResult.objects.filter(stay__guest__user=request.user) \
.select_related('stay', 'stay__guest')
forms = {}
for survey in survey_list:
forms[survey] = SurveyThreadForm(data=request.POST or None, survey=survey)
if forms[survey].is_valid():
instance = forms[survey].save(commit=False)
instance.survey = survey
instance.save()
return redirect('.')
通过以上两种方法,可以解决Django中“需要为字段“…”提供值,才能使用这个多对多关系”的错误。