简体   繁体   中英

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.

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM