0

I have a postgresql table with columns that have repeating data like this which was created using a django model:

enter image description here

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?

4
  • the same way you get any data from a query. just because it's select distinct doesn't change how you retrieve it. you'll get 0 or more rows of data that you fetch and store. Commented Apr 8, 2014 at 21:42
  • can you tell me how to get data using python? Commented Apr 8, 2014 at 21:47
  • Do you want to get this inside django or in a standalone python script? Commented Apr 8, 2014 at 21:48
  • i want to get it inside django. Commented Apr 8, 2014 at 21:48

1 Answer 1

1

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.

2
  • is this operation equivalent to the get operation? Commented Apr 8, 2014 at 21:56
  • 1
    no - get() will raise an exception if more than match is found and does not return a QuerySet object, while distinct() returns a QuerySet object which is iterable. They are both part of the QuerySet API though, and similar in the sense that you use them to access data stored in your database. Open you your django shell and try them out to see the difference Commented Apr 8, 2014 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.