gpt4 book ai didi

python - Django Rest序列化2级字段

转载 作者:行者123 更新时间:2023-11-30 23:27:13 24 4
gpt4 key购买 nike

您好,我需要在 2 级引用项的序列化器中添加一个字段。

我有以下模型:

模型.py:

class Company(models.Model):
companyName = models.CharField(max_length=50, blank=True)

class Poll(models.Model):
questionString = models.CharField(max_length=500, blank=True)
companyId = models.ForeignKey(Company, null=True, db_column='companyId', blank=True)

class PossibleAnswer(models.Model):
answerString = models.CharField(max_length=100, blank=True)
pollId = models.ForeignKey(Poll, null=True, db_column='pollId', blank=True,related_name='answers')
token = models.CharField(max_length=10, blank=True)

序列化器.py:

class PossibleAnswerSerializer(serializers.ModelSerializer):
#companyId = serializers.RelatedField()
class Meta:
model = PossibleAnswer
fields = ('answerString', 'token', 'pollId', 'companyId')

我想为PossibleAnswer对象创建一个序列化器,该对象有一个名为company的字段。如何做这个引用?类似于:django 查询集过滤器中的 pollId__companyId。

最佳答案

另一个解决方案...

class PossibleAnswerSerializer(serializers.ModelSerializer):
companyId = serializers.SerializerMethodField()

def get_companyId(self, obj):
return obj.pollId.companyId

class Meta:
model = PossibleAnswer
fields = ('answerString', 'token', 'pollId', 'companyId',)

关于python - Django Rest序列化2级字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com