如何在序列化器中获取外键字段



在序列化器中,类我试图获得类别详细信息,如"name"但是下面的代码给了我外键id

models.py


class Category(MP_Node, Timestamps):
name = models.CharField(_('Name'), max_length=255, db_index=True)

class VideoCategory(Category):
image = models.ImageField(upload_to='video_categories', blank=True, null=True, max_length=255)

class VideoCategoryVideo(BaseModel, Timestamps, SoftDelete):
video = models.ForeignKey(Video, on_delete=models.CASCADE)
category = models.ForeignKey(VideoCategory, on_delete=models.CASCADE, null=True)

serializers.py


class VideoCategoryVideoSerializer(serializers.ModelSerializer):
class Meta:
model = VideoCategoryVideo
fields = ('category', )
class VideosDetailsListSerializer(serializers.ModelSerializer):
category = serializers.SerializerMethodField()
class Meta:
model = Video
fields = ('id', 'create_date', 'category')
def get_category(self, data):
cate = VideoCategoryVideo.objects.filter(video=data.id)
category = VideoCategoryVideoSerializer(cate, many=True)
return category.data

结果是:

"category": [
{
"category": 1
}]

但预期结果是

"category": [
{
"name": "cate_name"
}]

您可以将CharField添加到VideoCategoryVideoSerializer中,并指定该值的source:

class VideoCategoryVideoSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='category.name', read_only=True)
class Meta:
model = VideoCategoryVideo
fields = ('category', 'name')

这将告诉序列化程序从相关类别中获取name的值。

相关内容

  • 没有找到相关文章

最新更新