【问题标题】:Tastypie apply_filters with distinct具有不同的美味 apply_filters
【发布时间】:2016-02-25 19:03:49
【问题描述】:

谁能帮帮我,我需要一个只有唯一用户的共享列表,只有最新的共享公关。用户(post__user)

我在API框架中使用了tastepie,希望有人能帮助我,我的模型布局如下::

class Post(models.Model):
    user = models.ForeignKey(User)
    ....

class Share(models.Model):
    post = models.ForeignKey(Post)
    user = models.ForeignKey(User, blank=True, null=True)
    ....

我的 Tastypie 资源:: 带有我的代码示例,但给了我所有的共享,而不仅仅是一个(最新的)公关。用户..希望有人可以提供帮助。

class ShareResource(ModelResource):
    ....
    ....
    def apply_filters(self, request, applicable_filters):
        distinct = request.GET.get('distinct', False) == 'True'
        if distinct:
            d = self.get_object_list(request).filter(**applicable_filters).values_list("post__user", flat=True).distinct()
            return Share.objects.filter(post__user__id__in=d)
        else:
            return self.get_object_list(request).filter(**applicable_filters)

【问题讨论】:

    标签: python django django-models tastypie


    【解决方案1】:

    嗯,看起来更像是一个 ORM 问题。

    d 将是一个由applicable_filters 过滤的共享过任何内容的唯一用户列表。然后,您正在查询已共享内容的用户列表中的某人共享的共享对象;但此查询将返回那些用户共享但不在applicable_filters 中的共享对象。此外,它还会返回重复项。

    我想你想要这个:

    class ShareResource(ModelResource):
        ....
        ....
        def apply_filters(self, request, applicable_filters):
            distinct = request.GET.get('distinct', False) == 'True'
            if distinct:
                # need to order Share objects so that the most recent one comes first
                return self.get_object_list(request).filter(**applicable_filters).order_by('id', '-created').distinct('id')
            else:
                return self.get_object_list(request).filter(**applicable_filters)
    

    注意,这可能仅适用于 Postgres。

    【讨论】:

    • 嗯,谢谢 ;) .. 我在我的开发设置中使用 sqlite3,是否有解决方法可以在没有 distinct([*fields]) 的情况下使其工作
    • 不确定。如果您不选择相关数据,它可能仍然有效,试一试。我认为 DISTINCT 通常对正在选择的任何字段进行操作。
    猜你喜欢
    • 2012-07-11
    • 2012-04-19
    • 2011-10-19
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多