0

我有一个名为 Connector 的模型,它有一个用于分析的外键以及与 ExternalAttribute 模型的多对多关系。ExternalAttribute 模型有一个静态属性对象列表。我希望用户能够从他们的配置文件中添加和删除 ExternalAttribute 模型的属性。

在表单中,我将 ExternalAttribute 中的所有对象下拉到 ModelMultipleChoiceField 中,它工作正常,但我无法保存选定的属性并将对象添加到连接器模型。

这是表单保存代码:

profile = Profile.objects.get(user = User.objects.get(username=self.cleaned_data['user']))

connector = Connector(profile=profile)
connector.profile = profile
connector.attributes = self.cleaned_data['selected_attributes']
connector.save()

当我尝试在表单中保存选定的属性时,我在堆栈跟踪中收到此错误:

ValueError: "<Connector: Connector object>" needs to have a value for field "connector" before this many-to-many relationship can be used.

我正在使用效率低下的数据库,必须使用这些模型。谢谢您的帮助。

4

1 回答 1

1

在保存 M2M 关系之前,必须保存对象 - 使其具有主键。将您的代码更新为

connector = Connector(profile=profile)
connector.profile = profile
connector.save()
connector.attributes = self.cleaned_data['selected_attributes']
connector.save()
于 2013-10-31T15:21:39.757 回答