Django.fun

Django model's __str__ with seperate fields

I have a model that return's a financial year and a description. Currently the attributes are combined into one value as one field.

enter image description here

As you can see, the year 2021 and description test. I can click on the field which brings me to the details page.

My code:

    class Meta:
    ordering = ['description', 'accounting_year', 'swift_code']
    verbose_name_plural = "Extractions"

def __str__(self):
    return f'{self.accounting_year} {self.description}'

What I would like to achieve, but can't figure out nor find it online is to split the two fields into separate columns. Thus, 2021 as a column and test as a column.

Furthermore, I would like to be able to sort or even filter, because one of the fields is extraction date. Would be great that an admin user could changed the order from newest to oldest and vice versa of just filter on name or date. Any documentation on that?

try this

In your apps/admin.py

from django.contrib import admin
from yourapp.models import Extraction

class ExtractionAdmin(admin.ModelAdmin):
    list_display = ['accounting_year', 'description']


admin.site.register(Extractions, ExtractionAdmin)

for filter refer https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.filter_horizontal

for sorting refer https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.sortable_by

Tutorials

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

Обработка периодических задач в Django с помощью Celery и Docker

View all tutorials →