Using double underscore to directly update foreign key's field in Django?

Issue

I am using double underscore to filter a model or get values from it in Django like this:

# filtering model
furthers = myModel.objects.filter(foreignKeyField__furtherField=value)

# getting values
furtherField = myModel.objects.get(id=10).values("foreignKeyField__furtherField")

But when I try to use update() method with double underscore like this:

myModel.objects.filter(id=10).update("foreignKeyField__furtherField")

I get an error:

django.core.exceptions.FieldDoesNotExist: myModel has no field named 'foreignKeyField__furtherField'

I looked up documentations about this but there is neither usage example of double underscore for update() method nor a word I cant use it like this way. So could we say update() method cannot be used like this?

Solution

You can’t update this way but you can update it other way round

You should use reverse foreign key relationship like this

ForeignModel.objects.filter(mymodel_set__id=10).update(foreign_key_field=some_value)

Answered By – Deepak Tripathi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published