本文介绍了在ModelForm中保存ModelMultipleChoiceField时如何解决ValueError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模型.py:
class RelayAddress(models.Model):
id = models.AutoField(primary_key=True,default=0)
sister_relay_relation = models.ManyToManyField('self', through='RelaySisterRelation',symmetrical=False)
def save(self, *args, **kwargs):
self.update_time = int(time.time())
super(RelayAddress,self).save(*args, **kwargs)
class RelaySisterRelation(models.Model):
id = models.AutoField(primary_key=True,default=0)
relay = models.ForeignKey(RelayAddress,related_name="relay")
sister_relay = models.ForeignKey(RelayAddress,related_name="sister_relay")
我的管理员.py
class RelaySisterRelationForm(forms.ModelForm):
relay=forms.ModelMultipleChoiceField(label=u'relay',widget=forms.CheckboxSelectMultiple(),queryset=RelayAddress.objects.all())
sister_relay=forms.ModelMultipleChoiceField(label=u'sister_relay',widget=forms.CheckboxSelectMultiple(),queryset=RelayAddress.objects.all())
def save(self, *args, **kwargs):
return super(RelaySisterRelationForm, self).save(*args,**kwargs)
我的view.py为null,然后出现ValueError:
And my view.py is null, then I get a ValueError:
Cannot assign "[<RelayAddress: RelayAddress object>]": "RelaySisterRelation.relay" must be a "RelayAddress" instance.
以及如何解决此问题.
推荐答案
RelaySisterRelation.relay
是 RelayAddress
的外键,这意味着它只能存储对一个的引用> RelayAddress
,但是您的 RelaySisterRelationForm.relay
使用 ModelMultipleChoiceField
(用于多对多关系),因此返回(可能为空) RelayAddress
实例.
RelaySisterRelation.relay
is a ForeignKey to RelayAddress
meaning it can only store a references to one RelayAddress
but your RelaySisterRelationForm.relay
uses ModelMultipleChoiceField
which is for many-to-many relations so returns a (potentially empty) list of RelayAddress
instances.
这篇关于在ModelForm中保存ModelMultipleChoiceField时如何解决ValueError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!