Search code examples
djangomany-to-manydjango-orm

<XXX> needs to have a value for field xxx before this many-to-many relationship can be used


I currently have the following 3 models

class modelToolName(models.Model):
    tool_name = models.CharField(max_length=250,unique=True)

class modelBodyPart(models.Model):
    part_name = models.CharField(max_length=128,unique=True)

class modelNormalBodyPartResult(models.Model):
    body_part = models.ForeignKey(modelBodyPart, default=None)
    tool_name = models.ManyToManyField(modelToolName, default=None, blank=True)
    result = models.TextField(blank=True, null=True)

Now I am attempting to insert value into the modelNormalBodyPartResult in this way

result="xxxx"
bodpart = modelBodyPart.objects.get(part_name="xxx") #--->returns object fine
toolqset = modelToolName.objects.get(tool_name="xxx")#--->returns object fine
modelNormalBodyPartResult.objects.create(body_part=bodpart,tool_name = toolqset,result=result) --->error

and I get the error

<modelNormalBodyPartResult: modelNormalBodyPartResult object> needs to have a value for field "modelnormalbodypartresult" before this many-to-many relationship can be used.

I looked at this post but still could not figure out the issue any suggestions in this regard would be appreciated.


Solution

  • You have to create an object first, then add the ManyToMany related objects to it,

    result="xxxx"
    bodpart = modelBodyPart.objects.get(part_name="xxx")
    toolqset = modelToolName.objects.get(tool_name="xxx")
    item = modelNormalBodyPartResult.objects.create(body_part=bodpart,result=result)
    item.tool_name.add(toolqset)
    item.save()