Use Serializermethodfield in the Django REST framework to optimize unnecessary queries

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.