python field readonly-ag凯发k8国际
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import readonlyfield [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)
总结
以上是ag凯发k8国际为你收集整理的python field readonly_python serializers.readonlyfield方法代码示例的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇:
- 下一篇: python简单爬虫手机号_python