I'm curious if there's any way to do a query in Django that's not a "SELECT * FROM...
" underneath. I'm trying to do a "SELECT DISTINCT columnName FROM ...
" instead.
Specifically I have a model that looks like:
class ProductOrder(models.Model):
Product = models.CharField(max_length=20, promary_key=True)
Category = models.CharField(max_length=30)
Rank = models.IntegerField()
where the Rank
is a rank within a Category
. I'd like to be able to iterate over all the Categories doing some operation on each rank within that category.
I'd like to first get a list of all the categories in the system and then query for all products in that category and repeat until every category is processed.
I'd rather avoid raw SQL, but if I have to go there, that'd be fine. Though I've never coded raw SQL in Django/Python before.
One way to get the list of distinct column names from the database is to use
distinct()
in conjunction withvalues()
.In your case you can do the following to get the names of distinct categories:
There are a couple of things to remember here. First, this will return a
ValuesQuerySet
which behaves differently from aQuerySet
. When you access say, the first element ofq
(above) you'll get a dictionary, NOT an instance ofProductOrder
.Second, it would be a good idea to read the warning note in the docs about using
distinct()
. The above example will work but all combinations ofdistinct()
andvalues()
may not.PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:
User order by with that field, and then do distinct.
The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.
or
And, it works without PostgreSQL.
This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python
set
, but it's great for noodling around the shell.It's quite simple actually if you're using PostgreSQL, just use
distinct(columns)
.Note that this feature has been included in Django since 1.4