What is doing __str__ function in Django?

前端 未结 6 2257
猫巷女王i
猫巷女王i 2021-02-13 13:09

I\'m reading and trying to understand django documentation so I have a logical question.

There is my models.py file

from django.db import mo         


        
6条回答
  •  生来不讨喜
    2021-02-13 13:48

    Django has __str__ implementations everywhere to print a default string representation of its objects. Django's default __str__ methods are usually not very helpful. They would return something like Author object (1). But that's ok because you don't actually need to declare that method everywhere but only in the classes you need a good string representation. So, if you need a good string representation of Author but not Blog, you can extend the method in Author only:

    class Author(models.Model):
        name = models.CharField(max_length=100)
        ...
    
        def __str__(self):
            return f'{self.name}'  # This always returns string even if self.name is None
    
    class Post(models.Model):
        author = models.ForeignKey(Author, on_delete=models.CASCADE)
        text = models.CharField(max_length=100)
    
    author = Author.objects.create(name='David')
    print(author)  # David
    
    post = Post.objects.create(author=author, text='some text')
    print(post)  # Post object(1)
    

    Now, beyond Django, __str__ methods are very useful in general in Python. More info here.

提交回复
热议问题