Smiling
Smiling

Reputation: 11

Django admin: Change the displayed value of a key

i have a model that includes a key "service_id" and the values stored in database are like "10001", i want to add a method to admin page that instead of displaying the id it displays a custom value like "Car Wash".

Upvotes: 1

Views: 1606

Answers (2)

Dos
Dos

Reputation: 2552

I think you need to create a custom field to be added in your list_display

from django.contrib import admin

@admin.register(MyModelClass)
class MyModelClassAdmin(admin.ModelAdmin):
    list_display = ('my_field')

    def my_field(self, obj):
        return obj.description().title()
    my_field.short_description = "My field" 

You can change the value returned by the my_field method as you prefer (take into consideration that you can use the obj instance).

Upvotes: 3

Ashwin Bande
Ashwin Bande

Reputation: 3073

Create an Admin Class following

class ModelclassNameAdmin(admin.ModelAdmin):
    list_display = ('service__name', [other fields])

in it for list display use double underscore __ for accessing field inside foreign key like service__name

and while registering the model add admin as second argument.

admin.site.register(ModelclassName, ModelclassNameAdmin)

Upvotes: 0

Related Questions