Django REST框架:向ModelSerializer添加附加字段 [英] Django REST Framework: adding additional field to ModelSerializer

查看:385
本文介绍了Django REST框架:向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')

什么是正确的方式去做这个?我看到您可以传递额外的上下文到序列化器,是否在上下文字典中传递附加字段的正确答案?使用这种方法,获取我需要的字段的逻辑不会与序列化器定义自包含,这是理想的,因为每个序列化的实例都需要 my_field 。在DRF序列化程序文档的其他地方,它额外的字段可以对应于模型上的任何属性或可调用。我在说什么是额外的领域?我应该在 Foo 的模型定义中定义一个返回 my_field 值的函数,在序列化器中我连接my_field到那个可调用?这是什么样子?

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? 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". Is extra fields what I'm talking about? 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?

提前感谢,如有需要,很乐意澄清问题。

Thanks in advance, 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框架:向ModelSerializer添加附加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆