1

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
  • If it work you can appreciate by up voting it. Commented Feb 7, 2017 at 5:12

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Piyush for the answer. In your example, I'm trying to update model2.teacher . I don't want to update al of the model2 models. I believe that is what your example does?
" don't want to update al of the model2 models", what do you mean?
model2.objects.filter(name=obj).update(teacher='Emile') would query for all model2's with obj. I have a specific instance I want to update, in this example 'watch'
I don't think so actually model2.objects.filter(name=obj) part just check the reference and filter and then .update() will update the whatever matching fields, this is what my understanding is correct me if I am wrong.
Ohh thanks , can you just modify it then so that I will get to know.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.