本文介绍了如何在模型序列化器中添加额外字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对django rest框架非常陌生.我有两个模型ModelA和ModelB.

I am very new to django rest framework. I have two models ModelA and ModelB.

我有ModelB Searilzer来显示get请求中的所有字段.

I have a ModelB searilzer to display all the fields in get request.

由于某些原因, ModelA和ModelB FK 无关,而是与 ModelA.objects.get(modelB.field1 = modelA.pk)相关>这将返回单个数据.

Because of some reasons ModelA and ModelB are not related by FK but ModelA.objects.get(modelB.field1=modelA.pk) this will return single data.

class ModelASerailzer(serializers.ModelSerializer):

   class Meta:
        model = ModelA
        fields = ['f1','f2']


class ModelBSerailzer(serializers.ModelSerializer):
      # I want to do something like this here
         extra_field = ModelA.objects.get(modelB.field1=modelA.pk).f1 # this will return the data in shell 
                 #and normal django view but I don't know how to implement this in django rest ?
    class Meta:
        model = ModelB
        fields = ['field1','field2', 'extra_field']

我尝试过这样

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

    def get_extra_field(self, member):
        return ModelA.objects.get(pk=member.field).f1
    class Meta:
      model = ModelB
      fields = ['field1','field2', 'extra_field']

与此有关,我得到了此错误 UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的起始字节

With this I got this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

ModelA.objects.get(pk = member.field).f1 是一个FileField.

ModelA.objects.get(pk=member.field).f1 is a FileField.

推荐答案

尝试一下(我尚未测试):

Try this (I haven't tested):

class ModelBSerializer(serializers.ModelSerializer):
    extra_field = serializers.SerializerMethodField('get_extra_field')

    def get_extra_field(self, member):
        return ModelASerializer(ModelA.objects.get(pk=member.field)).data

    class Meta:
      model = ModelB
      fields = ['field1','field2', 'extra_field']

这篇关于如何在模型序列化器中添加额外字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 13:41