Django:实例在多对多关系之前需要有主键值
在我看来,这是我的模型
class Business(models.Model):
business_type = models.ManyToManyField(BusinessType)
establishment_type = models.ForeignKey(EstablishmentType)
website = models.URLField()
name = models.CharField(max_length=64)
def __unicode__(self):
return self.name
,我正在尝试保存一条记录,如下所示:
business = BusinessForm(request.POST or None)
if business.is_valid():
busi = business.save(commit=False)
bt = BusinessType.objects.get(id=6)
busi.business_type = bt
et = EstablishmentType.objects.get(id=6)
busi.establishment_type = et
busi.save()
但是,它给了我一个错误,
'Business' instance needs to have a primary key value before a many-to-many relationship can be used.
我该如何保存它?
This is my model
class Business(models.Model):
business_type = models.ManyToManyField(BusinessType)
establishment_type = models.ForeignKey(EstablishmentType)
website = models.URLField()
name = models.CharField(max_length=64)
def __unicode__(self):
return self.name
in my view I'm trying to save a record as follows:
business = BusinessForm(request.POST or None)
if business.is_valid():
busi = business.save(commit=False)
bt = BusinessType.objects.get(id=6)
busi.business_type = bt
et = EstablishmentType.objects.get(id=6)
busi.establishment_type = et
busi.save()
However, it gives me an error
'Business' instance needs to have a primary key value before a many-to-many relationship can be used.
How do i save this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在添加任何 m2m 字段之前,您需要保存模型的实例。请记住,您必须使用
.add()
方法添加 m2m 字段,而不是像您所做的那样将其直接分配给该字段。请注意,当您执行
form_obj.save(commit=False)
时,save_m2m
方法在modelform
对象上可用。如果模型表单已给出 m2m 数据,则应使用 save_m2m 方法。如果您想像现在一样手动分配它,则需要像我上面的代码一样单独添加它。You need to save the instance of the model before adding any m2m fields. Remember you have to add the m2m field with the
.add()
method, not assign it directly to the field as you are doing.Note that the
save_m2m
method is available on themodelform
object when you doform_obj.save(commit=False)
. If the model form was given m2m data, you should use the save_m2m method. If you want to assign it manually like you're doing, you need to add it separately like my code above.如果有人仍在寻找这个问题的答案,我也遇到了同样的问题,并且无法在任何地方找到解决方案。
这是我出错的地方:
在我的模型中,我重写了 save() 方法,以便不将数据保存到数据库中。回想起来,这似乎是显而易见的,但重写 save() 方法导致了问题,因为我的主键从未真正生成。
祝你好运!
If anyone is out there still looking for answer to this, I was having the same issue and could not find a solution anywhere.
Here is where I had gone wrong:
In my model, I was overriding the save() method in order to not persist data to my database. It seems obvious in retrospect, but overriding the save() method was causing the issue because my primary key was never actually being generated.
Good luck!
在尝试分配给
busi.business_type
之前保存busi
。Save
busi
before attempting to assign tobusi.business_type
.尝试使用以下命令:
try it with this order: