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

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

但是,它给我一个错误

'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)

请注意, save_m2m code> modelform 对象,当您执行 form_obj.save(commit = False)。如果模型窗体被赋予了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天全站免登陆