[Answered ]-Django: ValueError when saving an instance to a ForeignKey Field

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)

Leave a comment