废话不多说,上代码 models.py

class Comment(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_related',
                               verbose_name='评论人', on_delete=models.CASCADE)
    create_date = models.DateTimeField('创建时间', auto_now_add=True)
    content = models.TextField('评论内容')
    parent = models.ForeignKey('self', verbose_name='父评论', related_name='%(class)s_child_comments', blank=True,
                               null=True, on_delete=models.CASCADE)
    rep_to = models.ForeignKey('self', verbose_name='回复', related_name='%(class)s_rep_comments',
                               blank=True, null=True, on_delete=models.CASCADE)

    class Meta:
        '''这是一个元类,用来继承的'''
        abstract = True

    def __str__(self):
        return self.content[:20]

class PhotosComment(Comment):
    pholong = models.ForeignKey(Photos,related_name='photoso_comments', verbose_name='所属图片',on_delete=models.CASCADE)

    class Meta:
        verbose_name = '图片评论'
        verbose_name_plural = verbose_name
        ordering = ['create_date']

------------
class Photos(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='照片作者', on_delete=models.PROTECT)
    title = models.CharField(max_length=68, verbose_name='照片描述')
    photos = models.ImageField(verbose_name="照片",upload_to="pho/%Y/%m/%d", null=True, blank=True)
    create_date = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    likes = models.IntegerField(verbose_name='点赞量', default=0)
    favorites = models.IntegerField(verbose_name='收藏', default=0)
    category = models.ForeignKey(Phototag, verbose_name='照片专辑', on_delete=models.PROTECT)
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')


    class Meta:
        verbose_name = '照片'
        verbose_name_plural = verbose_name
        ordering = ['-create_date']

关系序列化定义:

class PhotocommentSerializer(serializers.ModelSerializer):
    com_author = serializers.ReadOnlyField(source='author.nickname',label="评论人") #评论人
    com_author_img = serializers.CharField(source='author.avatar',read_only=True) #评论者头像
    com_date = serializers.SerializerMethodField() #评论时间

    def get_com_img(self,obj):
        print(dir(obj))
        return 111

    def get_com_date(self, obj):
        print(type(obj))
        return obj.create_date.strftime('%Y-%m-%d %H:%M:%S') if obj.create_date else ""

    class Meta:
        model = PhotosComment
        exclude = ('create_date',)


class PhotosListSerializer(serializers.ModelSerializer):
    author = serializers.ReadOnlyField(source='author.nickname')
    user_img = serializers.CharField(source='author.avatar',read_only=True)
    name_list = serializers.SerializerMethodField()
    date = serializers.SerializerMethodField()
    photoso_comments = PhotocommentSerializer(many=True,read_only=True)


    #图片专辑
    def get_name_list(self,obj):
        return obj.category.name

    def get_date(self, obj):
        return obj.create_date.strftime('%Y-%m-%d %H:%M:%S') if obj.create_date else ""

    class Meta:
        model = Photos
        # fields=["author"]
        exclude = ('is_delete','create_date',)

views方法

class PhotosListView(viewsets.ModelViewSet):
    queryset = Photos.objects.all()
    serializer_class = PhotosListSerializer
    permission_classes = (DjangoModelPermissionsOrAnonReadOnly,)

    def perform_create(self,serializer):
        serializer.save(author=self.request.user)

注:这个关系序列化有效的前提是必须在model定义中加 photoso_comments

否则在虚拟化结果中会找不到或者报错

测试拿到的json数据如下

{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 3,
            "author": "周杰伦",
            "user_img": "http://cdn.kkxl95.cn/FqGjvO1DS7aTpLBseU0HXezIjIGB",
            "name_list": "泰勒",
            "date": "2020-08-28 17:48:27",
            "photoso_comments": [
                {
                    "id": 5,
                    "com_author": "保持元气 ",
                    "com_author_img": "http://thirdqq.qlogo.cn/g?b=oidb&k=dccO9Yw09Jxhs1ngyrKQRA&s=40&t=1569737079",
                    "com_date": "2020-08-20 23:31:28",
                    "content": "呜呜呜,之前来体育西没去看霉霉!!",
                    "author": 23,
                    "parent": null,
                    "rep_to": null,
                    "pholong": 3
                },
                {
                    "id": 2,
                    "com_author": "周杰伦",
                    "com_author_img": "http://cdn.kkxl95.cn/FqGjvO1DS7aTpLBseU0HXezIjIGB",
                    "com_date": "2020-08-28 18:10:59",
                    "content": "这是霉霉吗???",
                    "author": 2,
                    "parent": null,
                    "rep_to": null,
                    "pholong": 3
                },
                {
                    "id": 4,
                    "com_author": "呼啦少女",
                    "com_author_img": "http://cdn.kkxl95.cn/xiaomai.jpg",
                    "com_date": "2020-08-28 18:30:50",
                    "content": "拜托,这就是霉霉!",
                    "author": 4,
                    "parent": null,
                    "rep_to": null,
                    "pholong": 3
                }
            ],
            "title": "明显",
            "photos": "http://cdn.kkxl95.cn//file/2020/08/28/e390153600af44d6b5ab81bab103bf9b.jpg",
            "likes": 1,
            "favorites": 3,
            "category": 2
        },
        {
            "id": 1,
            "author": "周杰伦",
            "user_img": "http://cdn.kkxl95.cn/FqGjvO1DS7aTpLBseU0HXezIjIGB",
            "name_list": "猫咪",
            "date": "2020-08-27 23:34:27",
            "photoso_comments": [
                {
                    "id": 1,
                    "com_author": "蔡徐坤",
                    "com_author_img": "http://cdn.kkxl95.cn/xiaomai.jpg",
                    "com_date": "2020-08-28 18:10:32",
                    "content": "好看的照片,什么猫来的",
                    "author": 3,
                    "parent": null,
                    "rep_to": null,
                    "pholong": 1
                },
                {
                    "id": 6,
                    "com_author": "呼啦少女",
                    "com_author_img": "http://cdn.kkxl95.cn/xiaomai.jpg",
                    "com_date": "2020-08-28 23:35:36",
                    "content": "哈哈哈她的英文歌好听",
                    "author": 4,
                    "parent": 5,
                    "rep_to": 5,
                    "pholong": 1
                }
            ],
            "title": "头像",
            "photos": "http://cdn.kkxl95.cn/file/2020/07/30/40aa429c6f7348f7a03c5c9cd12b4ca0.jpg",
            "likes": 2,
            "favorites": 0,
            "category": 1
        }
    ]
}

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://kkxl95.cn/article/1598539415/