如何解决ValueError在ModelForm中保存ModelMultipleChoiceField?

时间:2013-09-02 04:25:54

标签: python django

我的model.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")

我的admin.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:

Cannot assign "[<RelayAddress: RelayAddress object>]": "RelaySisterRelation.relay" must be a "RelayAddress" instance.

如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

RelaySisterRelation.relayRelayAddress的ForeignKey,意味着它只能存储对一个RelayAddress的引用,但您的RelaySisterRelationForm.relay使用ModelMultipleChoiceField -many relations因此返回RelayAddress个实例的列表(可能为空)。