Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show the correct name object in Django admin instead 'XXX object'

I've two apps in my Django Project and I created an ManytoManyField relationship between then. However, when I check it on my admin site, the references appears showing the model name plus object inside the Many to Many box.

I already tried write a str in my model as you can see below:

    def __str__(self):
        return str(self.course.name)

Below there is my models code.

from django.db import models
from cursos.models import Course

class Person(models.Model):
    name = models.CharField(max_length=50)
    course = models.ManyToManyField(Course, blank=True)

    def __str__(self):
        return str(self.course.name)

The image shows the page where I can register and relate some courses to a new person.

like image 872
aluiz Avatar asked Jan 31 '26 06:01

aluiz


1 Answers

This part of the form deals with editing the ManyToManyField. It will use the __str__ of the model that is referenced.

In order to thus change the textual representation, you need to implement the __str__ of the Course model, like:

class Course(models.Model):  # Course model, not Person
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

Setting the __str__ of a person to self.course.name does not seem correct, since you probably do not want to represent a Person by the name of its courses. Furthermore since this is a ManyToManyField, it will not work anyway.

Note: usually the name of ManyToManyFields is plural, so courses, instead of course, since it is basically a collection of Courses, not a single Course.

like image 158
Willem Van Onsem Avatar answered Feb 01 '26 19:02

Willem Van Onsem