在Django中做什么__str__函数? [英] What is doing __str__ function in Django?

查看:72
本文介绍了在Django中做什么__str__函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读并试图理解django文档,所以我有一个合理的问题.

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

有我的 models.py 文件

from django.db import models

# Create your models here.


class Blog(models.Model):
    name = models.CharField(max_length=255)
    tagline = models.TextField()

    def __str__(self):
        return self.name



class Author(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()

    def __str__(self):
        return self.name



class Post(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

每个类中每个 __ str __ 函数在这里做什么?我需要这些功能的原因是什么?

What is doing here each __str__ function in each class? What is the reason I need those functions in it?

推荐答案

您创建了Blog模型.迁移之后,Django将在数据库中创建一个带有名称"和标语"列的表.如果您想通过模型与数据库进行交互,例如创建模型的实例并保存或从db中检索模型;

You created Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database. If you wanna interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db;

def __str__(self):
        return self.name 

将派上用场.通过以下方式在项目的根文件夹中打开python交互式外壳程序:

will come handy. Open the python interactive shell in your project's root folder via:

python manage.py shell

然后

from projectName.models import Blog 
Blog.objects.all() //will get you all the objects in "Blog" table

此外,当您在管理面板中查看模型时,将看到列出的对象以及name属性.

Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.

问题是,如果您未添加该函数,则返回将如下所示:

The problem is, return will look like this if you did not add that function:

<QuerySet [<Blog:>,<Blog:>,<Blog:>....]

因此您将不知道这些对象是什么.识别这些对象的更好方法是通过将其设置为名称的属性之一来检索它们.这样,您将获得如下结果:

So you will not know what those objects are. Better way to recognize those objects is retrieving them by one of its properties which you set it as name. this way you will get the result as follow:

 <QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]

如果要对此进行测试:

python manage.py shell
from projectName.models import Blog
Blog.objects.create(name="first",tagline="anything") //will create and save an instance. It is single step. Copy-paste multiple times.
Blog.objects.all() //check out the result

这篇关于在Django中做什么__str__函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆