mardi 15 avril 2014

Comportement de querysets avec des clés étrangères dans Django - Stack Overflow


When a model object is an aggregate of many other objects, whether via Foreign Key or Many To Many, does iterating over the queryset of that object result in individual queries to the related objects?


Lets say I have


class aggregateObj(models.Model):
parentorg = models.ForeignKey(Parentorgs)
contracts = models.ForeignKey(Contracts)
plans = models.ForeignKey(Plans)

and execute


objs = aggregateObj.objects.all()

if I iterate over objs, does every comparison made within the parentorg, contracts or plan fields result in an individual query to that object?




Yes, by default every comparison will create an individual query. To get around that, you can make use of the select_related (and prefetch_related the relationship is in the 'backwards' direction) QuerySet method to fetch all the related object in the initial query:



Returns a QuerySet that will automatically “follow” foreign-key relationships, selecting that additional related-object data when it executes its query. This is a performance booster which results in (sometimes much) larger queries but means later use of foreign-key relationships won’t require database queries.





Yes. To prevent that, use select_related to fetch the related data via a JOIN at query time.



When a model object is an aggregate of many other objects, whether via Foreign Key or Many To Many, does iterating over the queryset of that object result in individual queries to the related objects?


Lets say I have


class aggregateObj(models.Model):
parentorg = models.ForeignKey(Parentorgs)
contracts = models.ForeignKey(Contracts)
plans = models.ForeignKey(Plans)

and execute


objs = aggregateObj.objects.all()

if I iterate over objs, does every comparison made within the parentorg, contracts or plan fields result in an individual query to that object?



Yes, by default every comparison will create an individual query. To get around that, you can make use of the select_related (and prefetch_related the relationship is in the 'backwards' direction) QuerySet method to fetch all the related object in the initial query:



Returns a QuerySet that will automatically “follow” foreign-key relationships, selecting that additional related-object data when it executes its query. This is a performance booster which results in (sometimes much) larger queries but means later use of foreign-key relationships won’t require database queries.




Yes. To prevent that, use select_related to fetch the related data via a JOIN at query time.


Related Posts:

0 commentaires:

Enregistrer un commentaire