简体   繁体   English

在Django模型中从PostgreSQL获取不同的列

[英]Getting distinct columns from postgresql in django model

I have a postgresql table with columns that have repeating data like this which was created using a django model: 我有一个PostgreSQL表,其中的列具有使用Django模型创建的重复数据,例如:

在此处输入图片说明

In order to get distinct values of a column, we use a postgre command something like this: 为了获得不同的列值,我们使用类似于以下的postgre命令:

SELECT distinct degree_code FROM studentapp_deg_course_cat

But i want to get this data as an array using python. 但是我想使用python获取此数据作为数组。 How do i get distinct objects from the columns of a table in python? 如何从python中的表的列中获取不同的对象?

In django you can use the distinct() method when querying your model. 在django中,查询模型时可以使用distinct()方法。

So something like this 所以像这样

models.YourModel.objects.order_by('degree_code').distinct('degree_code') 

As you are using PostgreSQL note the docs which state 当您使用PostgreSQL时,请注意docs指出的状态

On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply. 仅在PostgreSQL上,您可以传递位置参数(* fields)以指定DISTINCT应该应用的字段名称。 This translates to a SELECT DISTINCT ON SQL query. 这将转换为SELECT DISTINCT ON SQL查询。 Here's the difference. 这是区别。 For a normal distinct() call, the database compares each field in each row when determining which rows are distinct. 对于正常的distinct()调用,数据库在确定哪些行不同时会比较每行中的每个字段。 For a distinct() call with specified field names, the database will only compare the specified field names. 对于具有指定字段名称的distinct()调用,数据库将仅比较指定的字段名称。

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

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