Not possible to update foreign key by id for a queryset
|Reported by:||Owned by:||vaskalas|
|Component:||Database layer (models, ORM)||Version:||1.5|
|Severity:||Normal||Keywords:||update, related model, performance|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Attempting to minimize queries when updating list of ModelA instances that have foreign keys to ModelB, and I know the ids of the new ModelB instances I want to use for the instances of ModelA (that I only have the id for, not the instance).
ModelA.objects.filter(pk=id_of_a_instance).update(b_id=id_of_b_instance) which yields 'FieldNameDoesNotExist' because 'get_field_by_name' only has 'b' as a field name for ModelA, not b_id (which is strange given that is what is actually stored).
Then I try:
ModelA.objects.filter(pk=id_of_a_instance).update(b=id_of_b_instance), which says it needs an instance of ModelB, not a number.
Which means I will be stuck with an extra query:
model_b_list = list(ModelB.objects.filter(id_in=[list of ids for a instances])
and then have to iterate through the ModelA instances and assign the actual ModelB instances
Change History (7)
comment:4 Changed 2 years ago by
|Status:||closed → new|
|Triage Stage:||Unreviewed → Accepted|