Django admin custom descending and ascending field

Viewed 336

I am using Django Admin to visualize and edit data of my Model. One of the model's field is date and unfortunately is a CharField but with a validator ( dd.mm.yyyy ). I am trying to figure out of a solution to sort those dates in the correct way when the admin press on the sort button that is default from django. In my experience with Java it was all about overwriting the compare function of the class.

data_de_montat = models.CharField(help_text="eg: 02.07.2020 or 12.9.2021", max_length=15, validators=[
    RegexValidator(r'^[0-9]{1,2}.[0-9]{1,2}.[0-9]{4}$',
                   message='It should be dd.ll.aaaa',
                   code='wrong format'
                   )])

the button

2 Answers

In django it is very easy. You only need to go in to admin.py make a class with you model name and than add filter on create date which automatically sort out all dates for you. Example:

Step 1: Go to admin.py of your app

Step 2:Add following code

class YourModelAdmin(admin.ModelAdmin):
list_filter=['data_de_montat']

I managed to resolve this problem by adding 3 more calculated fields using annotate and combinatons of Database functions for formating my data. It's not the solution that I dreamed of but I handled it in a way. This code comes in the Admin Model.

    def get_queryset(self, request):
        qs = super(ProgramareAdmin, self).get_queryset(request)
        qs = qs.annotate(day=Cast(str("data_de_montat").split(".")[0], output_field=IntegerField()),
                         month=Cast(Substr("data_de_montat", StrIndex("data_de_montat", V('.')) + 1),
                                   output_field=IntegerField()),
                         year=Cast(Right("data_de_montat", 4), output_field=IntegerField()))
        return qs

    def day(self, obj):
        return obj.day

    def month(self, obj):
        return obj.month

    def year(self, obj):
        return obj.year

    day.admin_order_field = 'day'  # sortable new column
    month.admin_order_field = 'month'  # sortable new column
    year.admin_order_field = 'year'  # sortable new column

This works just for date using format like dd.mm.yyyy or d.m.yyyy & any combination of that.

Feel free to reply with a better solution or improvements for this method.

Related