📜  django __str__ self multiple - Python (1)

📅  最后修改于: 2023-12-03 15:30:28.401000             🧑  作者: Mango

Django str Method and Self Parameter

In Django, the __str__ method is used to define how an object should be represented as a string. It is a special method which is automatically called when you try to convert an object to a string.

The __str__ method is one of the most commonly used methods in Django models. It is used to provide a human-readable representation of the object.

When defining the __str__ method, the self parameter is used to refer to the current instance of the object. This parameter is required in all instance methods, including __str__.

Here is an example of defining the __str__ method in a Django model:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

In this example, the __str__ method returns the full name of the Person object using the self parameter to access the first_name and last_name attributes.

You can also use the __str__ method to return multiple fields as a string:

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    published_date = models.DateField()

    def __str__(self):
        return f"{self.title} by {self.author} ({self.published_date})"

In this example, the __str__ method returns the title, author, and published date of the Book object as a string.

In conclusion, the __str__ method is an essential part of Django models. It allows you to define how your objects are represented as strings, making them more readable and user-friendly. Remember to always include the self parameter when defining the __str__ method.