0

我有一个人们可以喜欢照片的网站。所以我创建了一个 PhotoResource 和一个 PhotoLikeResource(下面的代码)。我可以为照片添加点赞,但我还想返回照片的总点赞数以及当前用户是否已经喜欢它。我尝试在 hydrate 函数中返回信息(在代码中注释掉,但这破坏了 api 调用)。我怎样才能做到这一点?

class PhotoResource(ModelResource):
tags = fields.ManyToManyField(TagResource, 'tags', null=True, blank=True)
primary_image = fields.ForeignKey(ImageResource, 'primary_image', null=True, blank=True, full=True)
user = fields.ForeignKey(UserResource, 'user')

class Meta:
    queryset = Photo.objects.all()
    resource_name = 'photos'
    authorization = DjangoAuthorization()
    allowed_methods = ['get', 'post', 'put']
    filtering = {
        'primary_image': ALL,
        'featured': ALL
    }

# THE DEHYRDATE BELOW BREAKS THE photo_like CALL
# def dehydrate(self, bundle):
#     num_likes = PhotoLike.objects.filter(photo=bundle.obj).count()
#     bundle.data['num_likes'] = num_likes
#     user_like = PhotoLike.objects.filter(user=bundle.request.user, photo = bundle.obj).exists()
#     bundle.data['user_like'] = user_like
#     return bundle.data


class PhotoLikeResource(ModelResource):
photo = fields.ForeignKey(PhotoResource, 'photo', null=True, blank=True)

class Meta:
    queryset = PhotoLike.objects.all()
    authorization = DjangoAuthorization()
    resource_name = 'photo_like'
    always_return_data = True

def obj_create(self, bundle, **kwargs):
    return super(PhotoLikeResource, self).obj_create(bundle, user=bundle.request.user)

感谢您的时间和帮助:)

4

1 回答 1

1

那应该是return bundle而不是return bundle.data

发布您的回溯也很好。

于 2013-08-08T06:26:38.393 回答