gpt4 book ai didi

django save_model() 错误创建具有 m2m 字段的新对象

转载 作者:行者123 更新时间:2023-12-04 05:56:40 26 4
gpt4 key购买 nike

我有一个模型 models.py :

class MyModelClass(models.Model):
name = models.CharField(max_length=255)
m2m_1 = models.ManyToManyField(A, blank=True, null=True)
m2m_2 = models.ManyToManyField(B, blank=True, null=True)
fk = models.ForeignKey('C')
int = models.IntegerField()

和一个 admin.py类(class):
class MyModelClassAdmin(admin.ModelAdmin):
list_display = ('name',)

#Get all fields selected in MyModelClass m2m_2
def get_selected_in_m2m_2(self, obj):
sel = obj.m2m_2.all() #This line is the one for i get an error. The error is described below.
return sel

def save_model(self, request, obj, form, change):
"""When creating a new object, set the creator field.
"""
m2m_2_selected = self.get_selected_in_m2m_2(obj)
print m2m_2_selected

print request.user
if not change:
obj.creator = request.user
obj.save()

问题:
如果我已经单击“保存”按钮,一切正常 现有 我的管理页面中的 MyModelClass 对象。
但如果我尝试 创建 在管理页面中创建一个新模型对象并单击“保存”按钮(保存新对象,而不是更新现有对象),我会收到错误: 'MyModelClass' instance needs to have a primary key value before a many-to-many relationship can be used.
对不起我的英语不好。
任何帮助表示赞赏。
谢谢。

最佳答案

def save_model(self, request, obj, form, change):
"""When creating a new object, set the creator field.
"""
if not change:
obj.creator = request.user

super(MyModelClassAdmin, self).save_model(request, obj, form, change)

m2m_2_selected = self.get_selected_in_m2m_2(obj)
print m2m_2_selected
print request.user

关于django save_model() 错误创建具有 m2m 字段的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9443724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com