问题
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