简体   繁体   中英

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:

在此处输入图片说明

In order to get distinct values of a column, we use a postgre command something like this:

SELECT distinct degree_code FROM studentapp_deg_course_cat

But i want to get this data as an array using python. How do i get distinct objects from the columns of a table in python?

In django you can use the distinct() method when querying your model.

So something like this

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

As you are using PostgreSQL note the docs which state

On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply. This translates to a SELECT DISTINCT ON SQL query. Here's the difference. For a normal distinct() call, the database compares each field in each row when determining which rows are distinct. For a distinct() call with specified field names, the database will only compare the specified field names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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