Python rest_framework.serializers.PrimaryKeyRelatedField() Examples
The following are 1
code examples of rest_framework.serializers.PrimaryKeyRelatedField().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.serializers
, or try the search function
.
Example #1
Source File: factories.py From drf-schema-adapter with MIT License | 4 votes |
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)