class User(models.Model):
name = Charfield(...)
age = Integerfield(...)
...
class Article(models.Model):
user = ForeignKey(User, ...)
title = Charfield(...)
content = Charfield(...)
...
class ArticleView(ViewSet):
...
queryset = Article.objects.all().select_related('user')
queryset = Article.objects.all().prefetch_related('user')
class ArticleSerializer(ModelSerializer):
class Meta:
model = Article
fields = "__all__"
1. If I just apply select_related (or prefetch_related), will the user's information be added to my query set?
2. If so, when serializing the data, the information of the user who innerjoined through select_related is not shown in the serializer.data returned after serialization.
2-1. If I had to write additional code on my serializer, Which of the following options should I use?
class ArticleSerializer(ModelSerializer):
class Meta:
model = Article
fields = "__all__"
depth = 1
or
class ArticleSerializer(ModelSerializer):
user = UserSerializer()
class Meta:
model = Article
fields = "__all__"
2-2. The above options can get the same user's information without selecting_related(or prefetch_related), so why do you use select_related(or prefetch_related)?
Is there a difference in the number of DB lookup?
Yes,
select_relatedwill make a join query and filluserattribute with anUserinstance. Withoutselect_related, when you accessuserattribute, a extra query will be made to getUserinstance.select_related()
prefetch_related() is used for many-to-many and many-to-one relationship.
Because default serializer field for
ForeignKeyisPrimaryKeyRelatedFieldwhich represent the target of the relationship using its primary key.Refer to ModelSerializer document.
2-1. If I had to write additional code on my serializer, Which of the following options should I use?
depth=1is equal to define a nested model serializer withfields='__all__'for allForeignKeyandOneToOneField. So in your case, 2 serializers are same.Refer to source code
2-2. The above options can get the same user's information without selecting_related(or prefetch_related), so why do you use select_related(or prefetch_related)?
You shuld use
prefetch_related, because it use one query to fetchArticles andUsers. Say you have 100 articles, if you don't useprefetch_related, 100 extra query will be made when you accessarticle.user.Summary, serializer serialize data according to the fields defined by you, not according to the fields fetched in the queryset.
ModelSerializerhave default serializer fields for all the model fields, if the default serializer fields are not what you want, you should define serializer fields explicitly.