我想序列化一个模型,但想包括一个额外的字段,需要在模型实例上做一些数据库查询要序列化:

class FooSerializer(serializers.ModelSerializer):
  my_field = ... # result of some database queries on the input Foo object
  class Meta:
        model = Foo
        fields = ('id', 'name', 'myfield')

正确的做法是什么?我看到你可以传递额外的“上下文”序列化器,是正确的答案,在上下文字典中传递额外的字段?

使用这种方法,获取我需要的字段的逻辑将不包含在序列化器定义中,这是理想的,因为每个序列化实例都需要my_field。在DRF序列化器文档的其他地方,它说“额外的字段可以对应于模型上的任何属性或可调用”。我说的是“额外字段”吗?

我是否应该在Foo的模型定义中定义一个返回my_field值的函数,并在序列化器中将my_field连接到该可调用对象?它看起来像什么?

如果有必要,我很乐意澄清问题。


当前回答

正如化学程序员在这条评论中所说,在最新的DRF中,你可以这样做:

class FooSerializer(serializers.ModelSerializer):
    extra_field = serializers.SerializerMethodField()

    def get_extra_field(self, foo_instance):
        return foo_instance.a + foo_instance.b

    class Meta:
        model = Foo
        fields = ('extra_field', ...)

DRF文档来源

其他回答

在上一个版本的Django Rest Framework中,你需要在你的模型中创建一个带有你想要添加的字段名的方法。不需要@property和source='field'会引发错误。

class Foo(models.Model):
    . . .
    def foo(self):
        return 'stuff'
    . . .

class FooSerializer(ModelSerializer):
    foo = serializers.ReadOnlyField()

    class Meta:
        model = Foo
        fields = ('foo',)

我对类似问题的回答可能会有用。

如果你有一个模型方法定义如下:

class MyModel(models.Model):
    ...

    def model_method(self):
        return "some_calculated_result"

你可以像这样将调用该方法的结果添加到你的序列化器中:

class MyModelSerializer(serializers.ModelSerializer):
    model_method_field = serializers.CharField(source='model_method')

附注:因为自定义字段在你的模型中并不是一个真正的字段,你通常会想让它只读,像这样:

class Meta:
    model = MyModel
    read_only_fields = (
        'model_method_field',
        )

在序列化器类中添加以下内容:

def to_representation(self, instance):
    representation = super().to_representation(instance)
    representation['package_id'] = "custom value"
    return representation

如果你想读写额外的字段,你可以使用一个新的自定义序列化器,它扩展了序列化器。序列化器,像这样使用它

class ExtraFieldSerializer(serializers.Serializer):
    def to_representation(self, instance): 
        # this would have the same as body as in a SerializerMethodField
        return 'my logic here'

    def to_internal_value(self, data):
        # This must return a dictionary that will be used to
        # update the caller's validation data, i.e. if the result
        # produced should just be set back into the field that this
        # serializer is set to, return the following:
        return {
          self.field_name: 'Any python object made with data: %s' % data
        }

class MyModelSerializer(serializers.ModelSerializer):
    my_extra_field = ExtraFieldSerializer(source='*')

    class Meta:
        model = MyModel
        fields = ['id', 'my_extra_field']

我使用这个相关的嵌套字段与一些自定义逻辑

尽管这不是作者想要的,但它仍然可以被认为对这里的人有用:

如果您正在使用.save() ModelSerializer的方法,您可以将**kwargs传递给它。这样,您就可以保存多个动态值。

储蓄(**)