【问题标题】:how to get foreignkey fields in serializer如何在序列化程序中获取外键字段
【发布时间】:2021-10-09 12:01:38
【问题描述】:

在序列化程序中,我试图获取类别详细信息,例如“名称”,但以下代码为我提供了外键 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)

序列化器.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"
                    }]

【问题讨论】:

    标签: django-models django-rest-framework django-serializer


    【解决方案1】:

    您可以将CharField 添加到VideoCategoryVideoSerializer 并指定值的source,如下所示:

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

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

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2021-12-17
      • 2019-10-11
      • 2021-03-19
      • 1970-01-01
      • 2016-04-10
      相关资源
      最近更新 更多