It is possible to define a __str__
method on a model:
class Person(models.Model):
name = models.CharField(max_length=40)
hobbies = models.ManyToManyField(Hobby)
def __str__(self):
return self.name
But how to define something like this for an automatically generated table through a ManyToManyField? Objects that represent a relationship between a person and a hobby are written like this:
Person_hobbies object (1)
Note that I am not talking about the Hobby
object itself, but the object that represents the relation between a Person
and a Hobby
.
But how to define something like this for an automatically generated table through a
ManyToManyField
?
You can define the junction table model with the through=…
parameter [Django-doc]:
class Person(models.Model):
name = models.CharField(max_length=40)
hobbies = models.ManyToManyField(Hobby, through='PersonHobby')
def __str__(self):
return self.name
class PersonHobby(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
hobby = models.ForeignKey(Hobby, on_delete=models.CASCADE)
def __str__(self):
return f'A string with the {self.person} and the {self.hobby}'
Migrating to a junction model for a ManyToManyField
is however not that easy. If it is possible, I would delete migrations that include the ManyToManyField
and recreate a migration.