本文介绍了Django REST Framework:向 ModelSerializer 添加附加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化一个模型,但想包含一个额外的字段,该字段需要对要序列化的模型实例进行一些数据库查找:

I want to serialize a model, but want to include an additional field that requires doing some database lookups on the model instance to be serialized:

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

这样做的正确方法是什么?我看到 你可以传入额外的上下文" 对于序列化程序,在上下文字典中传递附加字段是正确的答案吗?

What is the right way to do this? I see that you can pass in extra "context" to the serializer, is the right answer to pass in the additional field in a context dictionary?

使用这种方法,获取我需要的字段的逻辑不会与序列化程序定义独立,这是理想的,因为每个序列化实例都需要 my_field.在 DRF 序列化器文档的其他地方 "额外的字段可以对应于模型上的任何属性或可调用".是额外字段"吗?我在说什么?

With that approach, the logic of getting the field I need would not be self-contained with the serializer definition, which is ideal since every serialized instance will need my_field. Elsewhere in the DRF serializers documentation it says "extra fields can correspond to any property or callable on the model". Are "extra fields" what I'm talking about?

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

Should I define a function in Foo's model definition that returns my_field value, and in the serializer I hook up my_field to that callable? What does that look like?

如有必要,很乐意澄清问题.

Happy to clarify the question if necessary.

推荐答案

我认为 SerializerMethodField 是您要找的:

I think SerializerMethodField is what you're looking for:

class FooSerializer(serializers.ModelSerializer):
  my_field = serializers.SerializerMethodField('is_named_bar')

  def is_named_bar(self, foo):
      return foo.name == "bar"

  class Meta:
    model = Foo
    fields = ('id', 'name', 'my_field')

http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

这篇关于Django REST Framework:向 ModelSerializer 添加附加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:56