Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading