2

In the Django Admin area, rather than have two separate columns for first_name and last_name to display, I'd like to concatenate those to create one column.

I want to avoid creating a separate model field to get this done. One solution could be to return self, but that seems to not work either.

The code below gets me "This site cannot be reached."

admin.py

from django.contrib import admin
from .models import Agent

class RealtorAdmin(admin.ModelAdmin):
  list_display = ('MLS_number', 'first_name' + 'last_name', 'email', 'phone', 'hire_Date')

PRMoureu
  • 12,817
  • 6
  • 38
  • 48
Ray Garza
  • 39
  • 7
  • See [this question](https://stackoverflow.com/questions/9164610/custom-columns-using-django-admin) for more examples. – Lord Elrond Sep 12 '19 at 18:53

2 Answers2

4

You can define a property in the model :

class Agent(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    @property
    def fullname(self):
        return '{} {}'.format(self.first_name, self.last_name)
        # return f'{self.first_name} {self.last_name}'  # with python 3.6+

And then call it in the fields :

class RealtorAdmin(admin.ModelAdmin):
  list_display = ('MLS_number', 'fullname', 'email', 'phone', 'hire_Date')
PRMoureu
  • 12,817
  • 6
  • 38
  • 48
4

Either define it as a property or method on the model, as PRMoureu showed, or define it directly on the ModelAdmin class:

class RealtorAdmin(admin.ModelAdmin):
  list_display = ('MLS_number', 'full_name', 'email', 'phone', 'hire_Date')

  def full_name(self, obj):
    return '{} {}'.format(obj.first_name, obj.last_name)

This is better if the admin is the only place you'll use this; otherwise the model is more appropriate.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895