如何将反向字段值添加到Django序列化器数据集中 [英] How do I add a reverse field value into the django serializer data set

查看:46
本文介绍了如何将反向字段值添加到Django序列化器数据集中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在包含子数据的对象中有一个父ID.我想将父ID的另一个字段值添加到序列化器中,以使子表返回到视图

I have a parent id in an object that contains child data. I want to add another field value from the parent id into the serializer for the child table to return back to the view

我制作了一个嵌套的序列化器,但是文献只着重于更新父对象和子对象.我只想更新子对象,但是我希望将父对象的字段添加到序列化程序的数据中.

I made a nested serializer, but the literature only focuses on updating the parent and child object. I only want to update the child object, but I want a field from the parent object added to the data of the serializer.

反向关系特别令人困惑,因为1.它对我不起作用,并且2.此处的示例在已用作正向关系示例的父项上使用了反向关系. https://www.django-rest-framework.org/api-guide/serializers/

The reverse relationship is especially confusing because 1. it didn't work for me, and 2. the example here uses it on a parent item which was already used as an example of a forward relationship. https://www.django-rest-framework.org/api-guide/serializers/

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ['choice_text', 'votes', 'question']

class QuestionSerializer(serializers.ModelSerializer):
    choice = ChoiceSerializer(many=True)

    class Meta:
        model = Question
        fields = ['id', 'question_text', 'choice']

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)# Create your models here.
    def __str__(self):
        return self.choice_text

s = ChoiceSerializer(data={'choice_text':'tests','votes': 50, 'question':1})
s.is_valid()
s.save()

我是从s.data获得的:ReturnDict([[('choice_text','tests'),('votes',50),('question',1)])

I got this from s.data: ReturnDict([('choice_text', 'tests'), ('votes', 50), ('question', 1)])

我希望这样:ReturnDict([[('choice_text','tests'),('votes',50),('question_test','hello')])

I would prefer this: ReturnDict([('choice_text', 'tests'), ('votes', 50), ('question_test', 'hello')])

推荐答案

此要求主要用于更改/添加来自模型实例序列化数据的其他信息,一种可行的方法是使用

Mostly for this requirement to change/add additional information from model instance serialize data one possible way to do that is to use SerializerMethodField.

此外,我们可能希望使用相同的序列化器来更新数据,以及获取序列化的数据以进行响应.在通过序列化器保存信息期间,我要表示的意思是我们需要 question 字段,但是在检索数据期间,我们需要 question_test .

In addition we may want to use same serializer for updating data and also for getting serialize data for response. what i want to mean during saving information through serializer we need question field but during retrive data we need question_test.

class ChoiceSerializer(serializers.ModelSerializer):
    question_test = serializers.SerializerMethodField()

    class Meta:
        model = Choice
        fields = ['choice_text', 'votes', 'question', 'question_test']
        extra_kwargs = {'question': {'write_only': True}}



    def get_question_test(self, obj):
        return obj.question.question_test

这篇关于如何将反向字段值添加到Django序列化器数据集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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