本文整理汇总了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)