Customize One-To-One Relation Dropdown in Django Admin

Viewed 45

I have a One-To-One relation on my users that connects them to their account how do i go about editing this dropdown that is provided by Django so as it will provide me with more detailed information directly in the dropdown box.

right now it says

Profile Object(1035)

I would like it to say something like

Username(ID)
1 Answers

You can override the __str__ method. So if you have a model named Profile, then you can implement this with:

from django.conf import settings

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

    def __str__(self):
        return f'{self.user}({self.pk})'

The __str__ method thus returns a string, and this string determines how the object looks like in drop down menus, etc.

Related