Opened 5 years ago

Closed 5 years ago

#14866 closed (duplicate)

select_related create multiple copies of the same object

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

Description

I am not sure this is a bug, it is more a surprising "feature" of the ORM, that is probably costing a lot of memory.

When using select_related on a query, the objects created because of their existence mentioned in select_related can be created multiple times if they are referred by many foreign keys.

I think this is still unclear, so here is an example :

Let say we have a model Order and Client

class Client(models.Model):
    #here fields

class Order(models.Model):
    #... here fields
    client = models.ForeignKey(Client)

If you execute the following code :

orders = Order.objects.all()
for order in orders:
    print "db id: " , order.client.id, "object id : " , id(order.client)

You will get multiple different object ids for a given db id if there are multiple orders referencing the same client.

This could easily be avoided, imho, by using a dict storing the db ids for which an object has already been created.

I do not see use cases where the current behaviour would be better, but I may be mistaken, and I clearly could be missing impacts on aggregation fuctions, or other parts of the ORM.

Change History (1)

comment:1 Changed 5 years ago by Alex

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to duplicate
  • Status changed from new to closed

Closing as a duplicate of #17.

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