Django: ValueError when saving an instance to a ForeignKey Field

佐手、 提交于 2020-01-05 03:51:18

问题


I am trying to save an instance of a model but get a ValueError.

ValueError: Cannot assign "<DataPointModel: DataPointModel object>": 
"Bike.data_point" must be a "DataPointModel" instance.

The model has a very simple field:

data_point = models.ForeignKey(DataPointModel, null=True, blank=True)

And the method is as well.

data_point = DataPointModel.objects.filter(
    object_id=bike.reference_model.id,
).last()
watch.data_point = data_point
watch.save()

Why is this not saving?


回答1:


Whenever you update or create anything in the table contains foreign Key you need to pass the object of primary key instead of passing real value.So you have to call the get query to primary key value table then pass that obj to foreign key column as a value.

Example :-

Suppose I have two model as follows:-

class model1(models.Model):
    name=models.CharField(primary_key=True,,max_length=2000)
    className=models.CharField(max_length=2000,null=True)

class model2(models.Model):
    name=models.ForeignKey(model1)
    teacher=models.CharField(max_length=2000,null=True)

views.py:-

jimmy = model2.objects.get(name="Jimmy")
obj = model1.objects.get(name='Piyush')
model2.objects.filter(id=jimmy.id).update(teacher=obj)


来源:https://stackoverflow.com/questions/42081593/django-valueerror-when-saving-an-instance-to-a-foreignkey-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!