Django:实例在多对多关系之前需要有一个主键值 [英] Django: instance needs to have a primary key value before a many-to-many relationship

查看:13
本文介绍了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

在我看来,我正在尝试按如下方式保存记录:

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.

我该如何保存?

推荐答案

在添加任何 m2m 字段之前,您需要保存模型的实例.请记住,您必须使用 .add() 方法添加 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.

if business.is_valid():
    busi = business.save(commit=False)
    et = EstablishmentType.objects.get(id=6)
    busi.establishment_type = et
    busi.save()
    bt = BusinessType.objects.get(id=6)
    busi.business_type.add(bt)

请注意,当您执行 form_obj.save(commit=False) 时,save_m2m 方法在 modelform 对象上可用.如果模型表单被赋予了 m2m 数据,你应该使用 save_m2m 方法.如果你想手动分配它,你需要像我上面的代码一样单独添加.

Note that the save_m2m method is available on the modelform object when you do form_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.

这篇关于Django:实例在多对多关系之前需要有一个主键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆