我目前有以下3个型号
android:background="@drawable/bg_txt">
现在我试图以这种方式将值插入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)
modelNormalBodyPartResult
我收到了错误
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
我看了this帖子,但仍然无法弄清楚这个问题,我们将不胜感激。
答案 0 :(得分:1)
您必须先创建一个对象,然后将ManyToMany
相关对象添加到其中,
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()