简体   繁体   English

如何添加新的序列化器字段以及所有模型字段?

[英]How to add new serializer field along with the all model fields?

Here I have a model which has so many fields.在这里,我有一个模型,它有很多领域。 So I want to use __all__ to return all the fields.所以我想用__all__来返回所有的字段。 But now I needed to add new field image_url so I customize a serializer like this but now with this I need to put all the model fields in the Meta class like this fields=['name','..', 'image_url'] in order to return the image_url .但是现在我需要添加新字段image_url所以我自定义了这样的序列化程序,但是现在我需要将所有模型字段放在Meta类中,就像这样fields=['name','..', 'image_url']为了返回image_url

Is there any way to return image_url without specifying it in the Meta.fields ?有没有办法返回image_url而不在Meta.fields指定它? I mean I don't want to write all the model fields in the Meta.fields (since the fields are too many) and want to return the image_url also.我的意思是我不想在Meta.fields写入所有模型字段(因为字段太多)并且还想返回image_url

serializers.py序列化程序.py

class MySerializer(ModelSerializer):
    image_url = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = MyModel
        fields = '__all__'
    def get_image_url(self, obj):
        return obj.image.url

You can try to subclass te serializer:您可以尝试子类化 te 序列化器:

class MySerializer(ModelSerializer):

    class Meta:
        model = MyModel
        fields = '__all__'


class MyChildSerializer(MySerializer):

    image_url = serializers.SerializerMethodField()

    class Meta:
        fields = MySerializer.Meta.fields + ['image_url']

    def get_image_url(self, obj):
        return obj.image.url

Never tried something like this, but since Meta.fields is a list you can perform basic python operations on it.从未尝试过这样的事情,但由于Meta.fields是一个列表,您可以对其执行基本的 Python 操作。

ps.附: If you're using pattern get_<field_name> for getter, you do not need to specify it in SerializerMethodField arguments.如果您使用模式get_<field_name>作为 getter,则无需在 SerializerMethodField 参数中指定它。

Try this:尝试这个:

class MySerializer(ModelSerializer):
    image_url = serializers.SerializerMethodField()

    class Meta:
        model = MyModel
        fields = [f.name for f in MyModel._meta.fields] + ['image_url']
    def get_image_url(self, obj):
        return obj.image.url

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM