Z
Z
zyusifov112021-04-22 20:28:59
Django
zyusifov11, 2021-04-22 20:28:59

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

2 answer(s)
M
Maxim, 2021-04-23
@zyusifov11

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)

At the output, you will have a list of dictionaries, where one dictionary is one table row with the field name and its value.

D
Dimonchik, 2021-04-22
@dimonchik2013

take from the category model immediately

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question