django rest framework 嵌套序列化

模型:作者和新闻

class Author(models.Model):
    """作者信息"""
    GENDER_CHOICES = (
        (0, "女"),
        (1, "男")
    )
    name = models.CharField(verbose_name="姓名", max_length=20)
    nick_name = models.CharField(verbose_name="昵称", max_length=20)
    mobile = models.CharField(verbose_name="手机号", max_length=11)
    email = models.EmailField(verbose_name="邮箱")
    gender = models.SmallIntegerField(verbose_name="性别", choices=GENDER_CHOICES, default=0)
    profile_picture = RichTextUploadingField(verbose_name="头像")

    class Meta:
        db_table = "tbl_author"
        verbose_name = "公众号作者"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class CompanyNews(models.Model):
    """公司新闻"""
    author = models.ForeignKey(to=Author, on_delete=models.CASCADE, related_name="company_news", verbose_name="作者")
    title = models.CharField(verbose_name="标题", max_length=50)
    digest = models.CharField(verbose_name="摘要", max_length=200)
    publish_time = models.DateTimeField(verbose_name="发布时间", auto_now=True)
    content = RichTextUploadingField(verbose_name="新闻内容")
    picture = RichTextUploadingField(verbose_name="封面图片")
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    update_time = models.DateTimeField(verbose_name="创建时间", auto_now=True)

    class Meta:
        db_table = "tbl_company_news"
        verbose_name = "公司动态"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

 序列化器

class AuthorSerializer(serializers.ModelSerializer):
    """作者序列化器"""

    class Meta:
        model = Author
        fields = "__all__"


class CompanyNewsSerializer(serializers.ModelSerializer):
    """公司动态序列化器"""
    author = serializers.SerializerMethodField()

    def get_author(self, obj):
        author_set = Author.objects.filter(id=obj.author_id)
        if author_set:
            return AuthorSerializer(instance=author_set.first()).data["nick_name"]
        else:
            return ""

    class Meta:
        model = CompanyNews
        fields = ("id", "title", "digest", "publish_time", "content", "picture", "create_time", "update_time", "author")

 查询视图

class CompanyNewsView(APIView):
    """公司动态"""

    def get(self, request):
        company_news_set = CompanyNews.objects.all().order_by("-create_time")[:9]
        company_news_data = CompanyNewsSerializer(instance=company_news_set, many=True).data
        return Response(data=company_news_data)

 响应数据

[
    {
        "id": 1,
        "title": "今天发工资了",
        "digest": "每个人都发了",
        "publish_time": "2021-01-14T11:02:21.679927+08:00",
        "content": "<p>朋友们发工资了</p>",
        "picture": "<div><a class=\"div_3446442004,2207547936\" href=\"https://image.baidu.com/search/detail?ct=503316480&amp;z=undefined&amp;tn=baiduimagedetail&amp;ipn=d&amp;word=%E5%9B%BE%E7%89%87&amp;step_word=&amp;ie=utf-8&amp;in=&amp;cl=2&amp;lm=-1&amp;st=undefined&amp;hd=undefined&amp;latest=undefined&amp;copyright=undefined&amp;cs=3446442004,2207547936&amp;os=845945707,358261802&amp;simid=3430506129,160107122&amp;pn=22&amp;rn=1&amp;di=84920&amp;ln=1468&amp;fr=&amp;fmq=1610592976272_R&amp;fm=&amp;ic=undefined&amp;s=undefined&amp;se=&amp;sme=&amp;tab=0&amp;width=undefined&amp;height=undefined&amp;face=undefined&amp;is=0,0&amp;istype=0&amp;ist=&amp;jit=&amp;bdtype=0&amp;spn=0&amp;pi=0&amp;gsm=0&amp;hs=2&amp;objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fa2.att.hudong.com%252F06%252F02%252F19300534106437134465026151672.jpg%26refer%3Dhttp%253A%252F%252Fa2.att.hudong.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1613184973%26t%3D2a6a47fae7bf705817144aadae8abf12&amp;rpstart=0&amp;rpnum=0&amp;adpicid=0&amp;force=undefined\" name=\"pn22\" style=\"display: block; width: 262px; height: 195px; margin-top: 0.38961px;\" target=\"_blank\"><img class=\"img-hover main_img\" src=\"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3446442004,2207547936&amp;fm=26&amp;gp=0.jpg\" style=\"background-color:#8fb2bf; height:195px; width:262px\" /></a></div>",
        "create_time": "2021-01-15T16:56:11.521337+08:00",
        "update_time": "2021-01-15T16:56:11.582421+08:00",
        "author": "张三"
    }
]

参考资料

 django rest framework 嵌套序列化

上一篇:解决办法:error: unknown type name ‘__int64‘


下一篇:PHP问题 —— undefined function mb_convert_encoding