I have a question about Django ORM Join.

Asked 2 years ago, Updated 2 years ago, 86 views

I'd like to ask you a question about join of Django om.

As far as I know, there are two ways to join using querySet.

1 model = model.objects.select_related('field_name')
2 model = model.objects.prefetch_related('field_name')

I heard that the method of 2 is available in all table relationships, but since sql runs more times than the method of 1, select_related() is used unless necessary.

I wonder which table relationship the method of 1 can be used only.

Thank you~

django orm

2022-09-22 20:29

1 Answers

prefetch_related() is well described.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

Summarize it roughly in Korean

It seems that the one who executes the SQL statement right away (number 1) is faster than joining in the language (number 2). Instead, select_related can only be written in the foreign-key/1:1 relationship.


2022-09-22 20:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.