Django Models: Preserving Object Identity Compared to Foreign Key

Django ORM (version 1.2.3) does not save the identifier with the following foreign keys back and forth. This is best explained with an example:

class Parent(models.Model):
    pass

class Child(models.Model):
    parent = models.ForeignKey(Parent)

parent = Parents.objects.get(id=1)
for child in parent.child_set.all():
    print id(child.parent), "=!", id(parent)

So, for each child, the parent is re-fetched from the database, although we know the parent at the time we get the child. This contradicts me.

In my case, this also leads to performance problems, as I perform some heavy operations at the parent level that I would like to cache at the instance level of the object. However, since the results of these calculations are available through a child = parent link, this caching at the parent level is useless.

Any ideas on how to solve this?

, , ForeignRelatedObjectsDescriptor ReverseSingleRelatedObjectDescriptor.

+2
2

.

, :

parent = Parents.objects.get(id=1)
for child in parent.child_set.all():
    child._parent_cache = parent

_FOO_cache - , Django , ForeignKey, , , , Django , child.parent.

, , - django-idmapper django-selectreverse - , .

+6

Django ORM "" . , , child.parent, .

( ) - Child select_related() . , , child.parent .

,

from django.db import connection

parent = Parents.objects.get(id=1)
print parent
print len(connection.queries) # say, X

children = Child.objects.select_related().filter(parent = parent)
for child in children:
    print child.parent

print len(connection.queries) # should be X + 1

Python parent child.parent , , child.parent .

+1

Source: https://habr.com/ru/post/1749516/


All Articles