class BlogListSerializer(serializers.Serializer): id = serializers.IntegerField() user = BlogUserInfoSerializer() title = serializers.CharField() like_user = serializers.ManyRelatedField(serializers.SlugRelatedField(slug_field="username", source="user_id"), queryset=User.objects.all(), source="follow") topic_name = serializers.SlugRelatedField(slug_field="name", source="topic", queryset=Topic.objects.all()) create_at = serializers.DateTimeField() class Blog(models.Model): follow = models.ManyToManyField(User, verbose_name="关注", related_name="follow_blog") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog") title = models.CharField(max_length=100) content = models.TextField(max_length=200000) topic = models.ForeignKey(Topic, null=True, verbose_name="话题", on_delete=models.CASCADE) create_at = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
class Topic(models.Model):
name = models.CharField(verbose_name="名称", max_length=100)
create_at = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
返回结果如下
{ "id": 158, "user": { "id": 50, "avatar": "https://xxx.xxx.cn/media/191b6193972a439e9886187f249bd2d9.jpg", "username": "语家", "sex": 2 }, "title": "想开个童装店?", "like_user": [ "13800138000" ], "topic_name": "#你们攒钱为了什么#", "create_at": "2018-10-15 16:21:36" }