[Python] How to define a string method for a many to many relation in Django?

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página