#31095 closed Cleanup/optimization (fixed)
Related Manager set() should prepare values before checking for missing elements.
Reported by: | TZanke | Owned by: | Hasan Ramezani |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description
To update a complete list of foreignkeys, we use set() method of relatedmanager to get a performance gain and avoid remove and add keys not touched by user.
But today i noticed our database removes all foreignkeys and adds them again. After some debugging i found the issue in this condition:
https://github.com/django/django/blob/master/django/db/models/fields/related_descriptors.py#L1004
Our form returns all Foreignkeys as list of strings in cleaned_data, but the strings do not match the pk (int). After converting the strings to int, before calling set(), fixes the problem.
Question:
How to avoid this issue? Maybe all code usages of set() are using lists of strings, maybe not. I dont know at the moment.
Is is possible Django fixes this issue? Should Django fix the issue? Maybe strings should raise an exception?
Change History (7)
comment:1 by , 5 years ago
Summary: | Django Related Manager set method → Django Related Manager set method may not work with pk strings |
---|
comment:2 by , 5 years ago
Easy pickings: | set |
---|---|
Summary: | Django Related Manager set method may not work with pk strings → Related Manager set() should prepare values before checking for missing elements. |
Triage Stage: | Unreviewed → Accepted |
Type: | Bug → Cleanup/optimization |
Version: | 1.11 → master |
comment:3 by , 5 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:4 by , 5 years ago
Has patch: | set |
---|
comment:6 by , 5 years ago
Thank you! Will this be back ported to any other Django version?
The following line looks very similar, should this also be fixed?
https://github.com/django/django/blob/master/django/db/models/fields/related_descriptors.py#L743
comment:7 by , 5 years ago
Thank you! Will this be back ported to any other Django version?
No, this patch doesn't qualify for a backport, it will be included in Django 3.1.
The following line looks very similar, should this also be fixed?
No, in this case set()
expects models instances, so it's not affected.
We cannot raise an exception on strings because
set()
accepts the field the relation points, e.g.CharField
. However we can optimize this with preparing values, i.e.