python - Django 明显不与 Postgres 一起工作

标签 python django postgresql django-rest-framework django-orm

我正在配置一个 API 来提取结果列表。这些项目是服装“产品”,有几个“变体”。

我正在尝试使用 distinct 来确保查询集只返回唯一产品的列表,而不是由于许多变化而重复多次的相同产品。

过去,我对产品的主键 (id) 使用了 distinct。但是,下面的代码不起作用。

当我尝试使用“distinct”时出现 500 错误。没有它-我没有错误。我无法在本地进行测试,因为 SQLite 不喜欢 distinct。我正在使用

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())

最佳答案

啊,刚刚想通了。

根据 django 文档 ( https://docs.djangoproject.com/en/1.9/ref/models/querysets/#distinct )

distinct 和 order_by 必须相同。

所以这不起作用:

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

但这会起作用:

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

这最有效:

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

使用选项 3 有什么问题吗?

关于python - Django 明显不与 Postgres 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36687397/

相关文章:

python - 在 Pgadmin4 中恢复数据库时出错

python - 如何区分音乐和 channel 的endevent?

python - Django 找不到对象时会返回什么?

python-3.x - 如何在 Django 中批量创建或更新

postgresql - Grails 如何正确加入 withCriteria

java - Jooq 错误 : missing FROM-clause entry for table for nested query(sum and group by)

Python 回车符不起作用

python-gdb 错误 : Python Exception <class 'RuntimeError' > Type does not have a target

python - 在 Python 中使用 beautifulsoup 从网站中提取数字

python - 选择基于数据库值 Django 检查哪个单选按钮