优化的可包含序列化程序字段。

djangorestframework-include-mixin的Python项目详细描述


django rest framework轻型可包含序列化程序字段

要求

用法

serializers.py

classGroupSerializer(SerializerIncludeMixin,ModelSerializer):@classproperty# django.utils.decoratorsdefextra_objects(cls):return{'users':UserSerializer(source='user_set',many=True),'active_users':UserSerializer(many=True),}classMeta:model=Groupfields=('id','name')

views.py

classGroupViewSet(QueryOptimizerMixin,ReadOnlyModelViewSet):"""    Groups.    list:    Available includable objects:      * users - all users;      * active_users - only active users.    """queryset=Group.objects.all()serializer_class=GroupSerializerselect_related={}prefetch_related={'users':'user_set','active_users':Prefetch(lookup='user_set',queryset=User.objects.filter(is_active=True),to_attr='active_users',),}

现在我们可以做到了:

client=APIClient()response=client.get(# GET /groups/?include[]=active_users'/groups/',data=[('include[]','active_users'),],)

这将只进行2次查询:

  • 所有组
  • 仅预取活动用户

文档

H2> RestyFraseWorkPixdioMyin。SerializerIncludeMixin < /H2>

在任何序列化程序中用于自动替换和添加序列化程序字段。

extra_objects类变量

key:str-来自get参数的值include[]。 例如,profile表示/users/?include[]=profile

value:序列化程序-任何字段序列化程序。

示例:

classUserSerializer(SerializerIncludeMixin,ModelSerializer):extra_objects={'profile':ProfileSerializer(),'groups':GroupSerializer(many=True),}classMeta:model=Userfields=('id','profile_id')
GET parametersResult serializer fields
'id': IntegerField(), 'profile_id': IntegerField()
?include[]=profile'id': IntegerField(), 'profile': ProfileSerializer()
?include[]=groups'id': IntegerField(), 'profile_id': IntegerField(), 'groups': GroupSerializer(many=True)
?include[]=profile&include[]=groups'id': IntegerField(), 'profile': ProfileSerializer(), 'groups': GroupSerializer(many=True)

注意:带/不带_id的标准序列化程序字段将替换为extra_objects中的字段。

对于?include[]=profileprofileprofile_id将从extra_objects替换为profile

< H2> RestyFraskWorkPixDyMixin

用于ModelViewSet以优化数据库查询。

select_related类变量

key:str-来自get参数的值include[]

value:str-可以传递给select相关(model manager function)的字段名。

prefetch_related类变量

key:str-来自get参数的值include[]

value:union[str,prefetch]-可以传递给预取相关(model manager function)的字段名或预取对象。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java将值插入sql表的选定列。使用c等参数#   IF语句的java JList数据添加   java在这种情况下有没有更好的方法来调整哈希值?   java@Valid不会触发@Repository中的验证   java如何在安卓中调整位图的大小   iTextJava。lang.NoClassDefFoundError:com/itextpdf/text/DocumentException   java使用ResourceBundleMessageSource加载一个ressource包(message.properties)的全部内容   java如何通过JasperReports 6动态设置Excel工作表名称。十、   java是编写这个程序的最佳方式   JAVA伊奥。FileNotFoundException:C:\Program Files\Apache软件基金会\Tomcat 8.0\。。\webapps\ROOT\\u cips\config。伊尼   java我正在尝试创建一个TictaToe程序,但是JOptionPane和绘图有问题   垃圾收集为什么java中的finalize()方法不在Finalizer类中?为什么它是在对象类中定义的?   java如何用括号编码替换url中的括号?   java web集成移动应用程序   在netbeans中运行MIDP2应用程序时出现java错误