[Fixed]-Django update on queryset to change ID of ForeignKey

13👍

You cannot update ForeignKey field with ID. You should pass the model object to update it. You can try

for fr,to in d.items():
    Test.objects.filter(id=fr).update(id=to)
    test_obj = Test.objects.get(id=to)
    Question.objects.filter(test_id=fr).update(test=test_obj)

Refer Documentation

Update:

From Django 1.8, you can use id of ForeignKey object to update an object.

for fr,to in d.items():
    Test.objects.filter(id=fr).update(id=to)
    Question.objects.filter(test_id=fr).update(test_id=to)
👤arulmr

18👍

Implemented in Django 1.8

Usage:

Bar.objects.filter(pk=foo.id).update(a_id=bar.id)
Bar.objects.filter(pk=foo.id).update(a=bar.id)

See ticket and commit.

Leave a comment