gpt4 book ai didi

python - Tastypie apply_filters 具有不同的

转载 作者:太空宇宙 更新时间:2023-11-03 16:53:39 27 4
gpt4 key购买 nike

有人可以帮我吗,我需要一个只有唯一用户的共享列表,只有最新的共享pr。用户(post__user)

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

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 资源::带有我的代码示例,但给了我所有的共享,而不仅仅是一个(最新的)pr。用户..希望有人可以提供帮助。

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)

最佳答案

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

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

我想你想要这个:

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。

关于python - Tastypie apply_filters 具有不同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35636070/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com