Django: instance needs to have a primary key value before a many-to-many relationship
This is my model
class Business(models.Model):
business_type = models.ManyToManyField(BusinessType)
establishment_type = models.ForeignKey(EstablishmentType)
website = models.URLField()
name = models.C开发者_开发知识库harField(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?
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.
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!
Save busi
before attempting to assign to busi.business_type
.
try it with this order:
if business.is_valid():
busi = business.save(commit=False)
et = EstablishmentType.objects.get(id=6)
busi.establishment_type = et
busi.save() #with commit == true
bt = BusinessType.objects.get(id=6)
busi.business_type = bt
busi.save() #here you save many to many
精彩评论