简体   繁体   English

Django独特不与Postgres一起使用

[英]Django distinct not working with Postgres

I'm configuring an API to pull a list of results. 我正在配置一个API以提取结果列表。 The items are clothing 'Products', which have several 'Variations'. 这些项目是服装“产品”,具有多个“变体”。

I am trying to use distinct to make sure the queryset only returns a list of unique products- instead of the same product repeated several times due to many variations. 我正在尝试使用distinct确保查询集仅返回唯一产品列表,而不是由于许多变化而多次重复同一产品。

In the past, I used distinct on product's primary key (id). 过去,我在产品的主键(id)上使用了distinct。 However, the below code is not working. 但是,以下代码不起作用。

I get a 500 error when I try using "distinct". 尝试使用“ distinct”时出现500错误。 Without it- I get no error. 没有它,我不会出错。 I cannot test locally as SQLite does not like distinct. 我不能在本地测试,因为SQLite不喜欢与众不同。 I am using 我在用

class InternalListView(APIView):

    renderer_classes = (JSONRenderer, )

    def get(self, request, *args, **kwargs):

        filters = {}
        for key, value in request.GET.items():
            key = key.lower()
            if key in countmatch:
                lookup, val = internalmatch[key](value.lower())
                filters[lookup] = val

        qset = (
            Product.objects
            .filter(**filters)
            .distinct('id')
            .order_by('-rating')
            .values('name', 'brand', 'rating')
            .annotate(
                price=F('variation__price__price'),
                id=F('pk'),
                vari=F('variation'),
            )
        )

        for i in qset:
            i['likes'] = random.randint(500, 1000)

        print qset

        return Response(qset.all())

Ahh just figured it out. 啊,只是想通了。

According to the django docs ( https://docs.djangoproject.com/en/1.9/ref/models/querysets/#distinct ) 根据django docs( https://docs.djangoproject.com/en/1.9/ref/models/querysets/#distinct

Both distinct & order_by have to be the same. 两者和&order_by必须相同。

So this does NOT work: 因此,这不起作用:

        .distinct('id')
        .order_by('-rating')

But this WILL work: 但这将起作用:

        .distinct('id')
        .order_by('id')

And this works best: 这最有效:

        .distinct('rating', 'id')
        .order_by('-rating')

Anything wrong with using option 3? 使用选项3有什么问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM