与Tastypie,AttributeError的反向关系

时间:2012-09-20 00:44:52

标签: python django django-models tastypie

我有一个资源,我正试图公开它的'投票。

class ViewPostResource(ModelResource):
    user = fields.ForeignKey(UserResource,'user',full=True)
    votes = fields.ToOneField('voting.resources.GetVotesResource', attribute='vote_set', full=True)
    class Meta:
        queryset = UserPost.objects.all()
        resource_name = 'posts'
        include_resource_uri = False

class GetVotesResource(ModelResource):
    user = fields.ForeignKey(UserResource,'user', full=True)

    class Meta:
        queryset = Vote.objects.all()
        resource_name = 'vote'

我的投票模式与正常情况有点不同。如何通过以下模型设置公开帖子的投票?

class Vote(models.Model):
    user         = models.OneToOneField(User, related_name='vote')
    content_type = models.ForeignKey(ContentType)
    object_id    = models.PositiveIntegerField()
    object       = generic.GenericForeignKey('content_type', 'object_id')
    vote         = models.SmallIntegerField(choices=SCORES)

1 个答案:

答案 0 :(得分:2)

我会改用“脱水”:

    def dehydrate(self, bundle):
        bundle.data['votes'] = Vote.objects.filter(object_id=bundle.obj.id, content_type=n).count() // or use aggregate to get total votes.
        return bundle.date

将“n”替换为正确的内容类型。