select_related create multiple copies of the same object
|Reported by:||madewulf||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.2|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
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.