当前位置: 首页>>代码示例>>Python>>正文


Python serializers.PrimaryKeyRelatedField方法代码示例

本文整理汇总了Python中rest_framework.serializers.PrimaryKeyRelatedField方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.PrimaryKeyRelatedField方法的具体用法?Python serializers.PrimaryKeyRelatedField怎么用?Python serializers.PrimaryKeyRelatedField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rest_framework.serializers的用法示例。


在下文中一共展示了serializers.PrimaryKeyRelatedField方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: serializer_factory

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import PrimaryKeyRelatedField [as 别名]
def serializer_factory(endpoint=None, fields=None, base_class=None, model=None):

    if model is not None:
        assert endpoint is None, "You cannot specify both a model and an endpoint"
        from .endpoints import Endpoint
        endpoint = Endpoint(model=model)
    else:
        assert endpoint is not None, "You have to specify either a model or an endpoint"

    if base_class is None:
        base_class = endpoint.base_serializer

    meta_attrs = {
        'model': endpoint.model,
        'fields': fields if fields is not None else endpoint.get_fields_for_serializer()
    }
    meta_parents = (object, )
    if hasattr(base_class, 'Meta'):
        meta_parents = (base_class.Meta, ) + meta_parents

    Meta = type('Meta', meta_parents, meta_attrs)

    cls_name = '{}Serializer'.format(endpoint.model.__name__)
    cls_attrs = {
        'Meta': Meta,
    }

    for meta_field in meta_attrs['fields']:
        if meta_field not in base_class._declared_fields:
            try:
                model_field = endpoint.model._meta.get_field(meta_field)
                if isinstance(model_field, OneToOneRel):
                    cls_attrs[meta_field] = serializers.PrimaryKeyRelatedField(read_only=True)
                elif isinstance(model_field, ManyToOneRel):
                    cls_attrs[meta_field] = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
                elif isinstance(model_field, ManyToManyRel):
                    # related ManyToMany should not be required
                    cls_attrs[meta_field] = serializers.PrimaryKeyRelatedField(
                        many=True,
                        required=False,
                        queryset=model_field.related_model.objects.all()
                    )
            except FieldDoesNotExist:
                cls_attrs[meta_field] = serializers.ReadOnlyField()

    try:
        return type(cls_name, (NullToDefaultMixin, base_class, ), cls_attrs)
    except TypeError:
        # MRO issue, let's try the other way around
        return type(cls_name, (base_class, NullToDefaultMixin, ), cls_attrs) 
开发者ID:drf-forms,项目名称:drf-schema-adapter,代码行数:52,代码来源:factories.py


注:本文中的rest_framework.serializers.PrimaryKeyRelatedField方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。