【问题标题】:Reverse Relationship with Tastypie, AttributeError与 Tastypie 的反向关系,AttributeError
【发布时间】:2012-09-20 00:44:51
【问题描述】:

我有一个资源,我试图在其中公开它的投票。

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)

【问题讨论】:

    标签: python django django-models tastypie


    【解决方案1】:

    我将改用“脱水”:

        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”替换为正确的内容类型。

    【讨论】:

    • 我并没有试图返回计数,我试图返回带有 user_id 的整个 Vote 对象。知道该怎么做吗?
    • 你应该仍然可以使用脱水。您只需要一一映射您需要的字段。或者,它可以是 bundle.data['vote'] = Vote.objects.get(user=bundle.object.user).__dict__ .
    • 这引导我朝着正确的方向前进,但我在 .filter() 而不是 .get() 上调用 .values() - 知道为什么它作为字符串中的 dict 返回而不仅仅是一个字典?
    猜你喜欢
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2017-05-31
    • 2012-09-24
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多