Opened 4 years ago

Closed 4 years ago

Last modified 4 years ago

#31759 closed Uncategorized (invalid)

Why do instance hints in ForwardManyToOneDescriptor use the related object?

Reported by: Daniel Miller Owned by: nobody
Component: Database layer (models, ORM) Version: 3.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Why do the instance hints in ForwardManyToOneDescriptor use the related object rather than the instance of the class being routed?

django/db/models/fields/related_descriptors.py:223

if instance._state.db is None:
    instance._state.db = router.db_for_write(instance.__class__, instance=value)
if value._state.db is None:
    value._state.db = router.db_for_write(value.__class__, instance=instance)

I would expect that to read like so

if instance._state.db is None:
    instance._state.db = router.db_for_write(instance.__class__, instance=instance)
if value._state.db is None:
    value._state.db = router.db_for_write(value.__class__, instance=value)

It looks like it may be a historical artifact from long ago, which was later converted to what we see today.

The documentation on multi-db hints is vague, it says the instance is "an object instance that is related to the read or write operation that is underway." While this is technically not inaccurate, it seems non-intuitive to pass a related object rather than the object being routed.

Change History (1)

comment:1 by Carlton Gibson, 4 years ago

Resolution: invalid
Status: newclosed

Hiya. This kind of enquiry isn't really appropriate for the issue tracker. Please see TicketClosingReasons/UseSupportChannels.

The instance kwarg is precisely the other object in the relation, so value for instance and instance for value, allowing the router to adjust the write DB depending on the related model.
Making your change, there's a failure in tests/multiple_database. I'd guess digging through that would reveal more.

Last edited 4 years ago by Carlton Gibson (previous) (diff)
Note: See TracTickets for help on using tickets.
Back to Top