Home > Software engineering >  Using double underscore to directly update foreign key's field in Django?
Using double underscore to directly update foreign key's field in Django?

Time:05-06

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?

CodePudding user response:

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)
  • Related