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)

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, socourses, instead ofcourse, since it is basically a collection ofCourses, not a singleCourse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With