Opened 3 years ago

Closed 22 months ago

Last modified 22 months ago

#21144 closed Cleanup/optimization (fixed)

Not possible to update foreign key by id for a queryset

Reported by: dakinsloss@… Owned by: vaskalas
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords: update, related model, performance
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: 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:1 Changed 3 years ago by dakinsloss@…

Resolution: invalid
Status: newclosed

My mistake--this should not have been submitted, was still debugging and this is not an issue.

comment:2 Changed 3 years ago by mbhagya@…

Sorry but what happened to this bug? Is this fixed in a later version? Because I can still see this in 1.5.

comment:3 Changed 2 years ago by Anthony Lalande

Could I ask for additional clarifications regarding why this issue was closed and set to invalid? This seems like a legitimate use case to support, no?

comment:4 Changed 2 years ago by Carl Meyer

Resolution: invalid
Status: closednew
Triage Stage: UnreviewedAccepted

Looks like the original reporter closed it without much explanation. I'm reopening, because I agree this is a valid case and should be supported somehow (I think probably by accepting raw IDs for an FK field in update).

comment:5 Changed 22 months ago by vaskalas

Owner: changed from nobody to vaskalas
Status: newassigned

comment:6 Changed 22 months ago by vaskalas

Resolution: fixed
Status: assignedclosed

Issue was fixed in commit c21e86ab9e3e5ebd6d245d038cb0cb352cd84c3a. Added unit tests to verify fix in

comment:7 Changed 22 months ago by vaskalas

The unit test was added actually added in this commit,

Note: See TracTickets for help on using tickets.
Back to Top