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

后端 未结 4 1867
时光取名叫无心
时光取名叫无心 2020-12-09 12:03

This is my model

class Business(models.Model):
    business_type = models.ManyToManyField(BusinessType)
    establishment_type = models.ForeignKey(Establishm         


        
4条回答
  •  北海茫月
    2020-12-09 12:53

    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)
    

    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.

提交回复
热议问题