gpt4 book ai didi

django - 在 DRF 中使用 Serializer 获取 StringRelatedField 和 PrimaryKeyRelatedField

转载 作者:行者123 更新时间:2023-12-02 03:36:29 28 4
gpt4 key购买 nike

很抱歉提出这个新手问题,但我根本找不到阅读手册的方法。

型号

    #Subject
class TemaPai(models.Model):
subject = models.TextField()
disciplines = models.ManyToManyField(Materia)

# order = models.IntegerField(blank=True, null=True)

def __str__(self):
return self.subject

class Meta:
verbose_name_plural = "temas-pais (subjects)"


# Order and junction
class TemaPaiOrdem(models.Model):
subject = models.ForeignKey(TemaPai, on_delete=models.CASCADE)
discipline = models.ForeignKey(Materia, on_delete=models.CASCADE)
order = models.IntegerField()

def __str__(self):
var2 = self.subject.subject
var = self.discipline.discipline
return var2 + ' - ' + var

class Meta:
verbose_name_plural = "Temas-pais-ordem"
unique_together = ('subject', 'discipline')

序列化器

class TemaPaiSerializer(serializers.ModelSerializer):

disciplines = serializers.PrimaryKeyRelatedField(many=True, queryset=Materia.objects.all())
class Meta:
model = TemaPai
fields = ('id', 'subject', 'url', 'disciplines')


class TemaPaiOrdemSerializer(serializers.ModelSerializer):

discipline = serializers.PrimaryKeyRelatedField(queryset=Materia.objects.all())
subject = serializers.PrimaryKeyRelatedField(queryset=TemaPai.objects.all())
class Meta:
model = TemaPaiOrdem
fields = ('id', 'subject','discipline', 'order')

好吧,TemaPaiOrdemSerializer 给了我一个这样的列表:

[
{
"id": 1,
"subject": 1,
"discipline": 1,
"order": 1
},
{
"id": 2,
"subject": 2,
"discipline": 1,
"order": 11
}
]

没关系。但我也想检索主题字符串表示形式(来自 TemaPai 模型),作为 read_only 字段。所以我想要的列表是这样的:

[
{
"id": 1,
"subject": 1,
"subject_name": "Introduction",
"discipline": 1,
"order": 1
},
{
"id": 2,
"subject": 2,
"subject_name": "Advanced stuff",
"discipline": 1,
"order": 11
}
]

我正在尝试使用

subject_name = serializers.ReadOnlyField(source:'subject')

没有成功。任何提示将不胜感激。

最佳答案

使用,

subject_name = serializers.StringRelatedField(source='subject',read_only=True)


因此你的序列化器将是这样的,

class TemaPaiOrdemSerializer(serializers.ModelSerializer):
discipline = serializers.PrimaryKeyRelatedField(queryset=Materia.objects.all())
subject = serializers.PrimaryKeyRelatedField(queryset=TemaPai.objects.all())
subject_name = serializers.StringRelatedField(source='subject',read_only=True)

class Meta:
model = TemaPaiOrdem
fields = ('id', 'subject', 'subject_name', 'discipline', 'order')

关于django - 在 DRF 中使用 Serializer 获取 StringRelatedField 和 PrimaryKeyRelatedField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50062036/

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