Answer the question
In order to leave comments, you need to log in
How to get unique values from Django orm base?
I have a database in which there are categories for example 10 sports category records 5 politics records, so here's how I get a list of these categories so that it comes out in the 1st category, that is:
Sports
Politics
Here is the result.
thanks in advance
Answer the question
In order to leave comments, you need to log in
ORM won't work without models. If you need to access a table for which no relevant model has been created, then you will have to query that table directly.
from typing import Any, Dict, List
from django.db import connection
with connection.cursor() as cursor:
cursor.execute('SELECT DISTINCT category_name FROM some_table_name;')
columns = [col[0] for col in cursor.description]
rows: List[Dict[Any, Any]] = []
row = cursor.fetchone()
while row:
rows.append(dict(zip(columns, row)))
row = cursor.fetchone()
print(rows)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question