【问题标题】:Trying to add like functionality to my Photo Resource using Tastypie尝试使用 Tastypie 向我的照片资源添加类似功能
【发布时间】:2013-08-08 01:42:11
【问题描述】:

我有一个人们可以喜欢照片的网站。所以我创建了一个 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)

感谢您的时间和帮助:)

【问题讨论】:

    标签: django rest tastypie


    【解决方案1】:

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

    发布您的回溯也很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2020-04-05
      • 2023-03-29
      • 2012-10-15
      • 2011-09-22
      相关资源
      最近更新 更多