Python-Django-将序列化器和属性作为参数传递

时间:2018-11-21 16:06:56

标签: python django generics attributes serializer

当前我正在处理此代码段:

def to_representation(self, instance):
    representation = super().to_representation(instance)

    representation['categories'] = CategorySerializer(instance.categories, many=True).data

    return representation

现在我要制作摘录

representation['categories'] = CategorySerializer(instance.categories, many=True).data

更通用,因此我可以在此处传递任何字段及其对应的序列化程序,例如:

representation[config['field']] = config['serializer'](instance[getattr(instance, config['field'])]).data

但是它完全崩溃了,有人处理过这种通用设置吗?

谢谢问候!

1 个答案:

答案 0 :(得分:0)

您想做什么:

instance[getattr(instance, config['field'])]

这似乎有太多的间接级别,也许您只想这样做:

getattr(instance, config['field'])

相反。我也很想将配置成员保存在本地以提高可读性:

field = config['field']
serializer = config['serializer']
representation[field] = serializer(getattr(instance, field)).data

看起来更具可读性