Use Serializermethodfield in the Django REST framework to optimize unnecessary queries
First look at an example, in general, for objects that have parent-child relationships, we use the following method to create the class.
A article class in which a article object can have multiple comment instances, the class in Django is defined as follows:
#coding: Utf-8 fromDjango.dbImportModels fromDjango.contrib.auth.modelsImportUser class article(models. Model):title = models. Charfield (' article title ', max_length=1024x768, blank=False) Summary = models. TextField (' article introduction ', blank=False) content = models. TextField (' article content ', blank=True, null=True) Create_user = models. ForeignKey (User, related_name=' Article_create_user ', verbose_name=' Create user ') Create_time = models. Datetimefield (' Create Time ', auto_now_add=True) def __str__(self): returnSelf.title def __unicode__(self): returnSelf.title class Meta:ordering = ('-create_time ',) class Comment(models. Model):Article = models. ForeignKey (article, related_name=' article_comments ', verbose_name=' article ') Comment = models. Charfield (' comments ', max_length=1024x768, blank=False) Create_user = models. ForeignKey (User, related_name=' Article_comments_create_user ', verbose_name=' Create user ') Create_time =models. Datetimefield (' Create Time ', auto_now_add=True) def __str__(self): returnSelf.comment def __unicode__(self): returnSelf.comment class Meta:ordering = ('-create_time ',)
Based on the definition of the above class, we typically define the serializer class as follows in the Django REST framework.
Add an attribute article_comments in the Articleserializer class to hold all the comment collections for the current article object. But there is a problem at this point if the article object has more Comment, this can affect performance. Like what:
#coding: Utf-8 fromRest_frameworkImportserializers from. ModelsImportArticle, Comment class articleserializer(serializers. Modelserializer):Article_comments = serializers. Primarykeyrelatedfield (many=True, required=False, read_only=True) class Meta:Model = Article fields = (' id ',' title ',' summary ',' content ',' Create_user ',' Create_time ',' article_comments ') class commentserializer(serializers. Modelserializer): class Meta:Model = Comment Fields = (' id ',' article ',' comment ',' Create_user ',' Create_time ')
In fact, in many cases we do not need to query the article object when querying the Comment object, many times we just need a article to have the total number of Comment objects can be, if there is a need to query Comment list details. At this point we can use the Serializermethodfield provided by the Django REST framework for this purpose. As follows:
#coding: Utf-8 fromRest_frameworkImportserializers from. ModelsImportArticle, Comment class articleserializer(serializers. Modelserializer):Article_comments_count = serializers. Serializermethodfield () class Meta:Model = Article fields = (' id ',' title ',' summary ',' content ',' Create_user ',' Create_time ',' Article_comments_count ') def get_article_comments_count(self, obj): returnObj.article_comments.all (). Count () class commentserializer(serializers. Modelserializer): class Meta:Model = Comment Fields = (' id ',' article ',' comment ',' create_user_id ',' Create_user_name ',' Create_time ')
- First, the article_comments attribute is removed in Articleserializer;
- Then add an attribute article_comments_count to the Articleserializer and append this attribute to the Meta fields list;
- Add a Get_article_comments_count method with a naming convention that adds a "get_" prefix to the attribute declared above and accepts an obj parameter, which is the current article object instance.
At this point, only the total number of Comment is displayed in the API for viewing article without a specific list.
Use Serializermethodfield in the Django REST framework to optimize unnecessary queries