欢迎访问 生活随笔!

尊龙游戏旗舰厅官网

当前位置: 尊龙游戏旗舰厅官网 > 编程语言 > python >内容正文

python

python field readonly-尊龙游戏旗舰厅官网

发布时间:2024/10/14 python 25 豆豆
尊龙游戏旗舰厅官网 收集整理的这篇文章主要介绍了 python field readonly_python serializers.readonlyfield方法代码示例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

# 需要导入模块: 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)

总结

以上是尊龙游戏旗舰厅官网为你收集整理的python field readonly_python serializers.readonlyfield方法代码示例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得尊龙游戏旗舰厅官网网站内容还不错,欢迎将尊龙游戏旗舰厅官网推荐给好友。

网站地图