我有一个人们可以喜欢照片的网站。所以我创建了一个PhotoResource和一个PhotoLikeResource(下面的代码)。我可以为照片添加相似内容,但我还想返回照片总喜欢的数量,以及当前用户是否已经喜欢它。我尝试在水合功能中返回信息(在代码中注释掉了,但这打破了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)
感谢您的时间和帮助:)
答案 0 :(得分:1)
应该是return bundle
而不是return bundle.data
。
发布追溯也很不错。