Django: instance needs to have a primary key value before a many-to-many relationship

Eva*_*611 11 django django-models django-views

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
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

However, it gives me an error

'Business' instance needs to have a primary key value before a many-to-many relationship can be used.
Run Code Online (Sandbox Code Playgroud)

How do i save this?

Jos*_*ton 27

您需要在添加任何m2m字段之前保存模型的实例.请记住,您必须使用.add()方法添加m2m字段,而不是像您一样直接将其分配给字段.

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)
Run Code Online (Sandbox Code Playgroud)

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