#36344: Accessing a related field after using defer() or only() unexpectedly
overwrites unsaved state on model instances
-------------------------------------+-------------------------------------
     Reporter:  Erick                |                    Owner:  (none)
         Type:  Uncategorized        |                   Status:  closed
    Component:  Database layer       |                  Version:  5.2
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:  invalid
     Keywords:                       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Comment (by Simon Charette):

 Accessing deferred fields in `__init__` is going to cause you a lot of
 trouble #22858, #31435, #32660 and
 
[https://docs.djangoproject.com/en/5.2/ref/models/instances/#django.db.models.Model
 is documented to be problematic].

 It causes a silent N+1 query which explains why your value is overriden
 when `value` is not part of the inclusion mask (accessing `self.value`
 will cause it to be retrieved it from the database and then assigned on
 the model instance).

 If you ''really need'' to implement field retrieval in `__init__` you
 should
 
[https://docs.djangoproject.com/en/5.2/ref/models/instances/#django.db.models.Model.get_deferred_fields
 gate these retrieval behind get_deferred_fields].


 {{{#!python
 def __init__(self, *args, **kwargs):
     super().__init__(self, *args, **kwargs)
     if "value" not in self.get_deferred_fields():
         self.value
 }}}
-- 
Ticket URL: <https://code.djangoproject.com/ticket/36344#comment:3>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/django-updates/010701965dc04a65-4147fa60-4dc5-429a-b45e-94d0f68bc859-000000%40eu-central-1.amazonses.com.

Reply via email to