代码之家  ›  专栏  ›  技术社区  ›  MD SHAYON

python django shell attributeError:'article'对象没有属性'title'

  •  0
  • MD SHAYON  · 技术社区  · 8 年前

    enter image description here 我是刚来Django的,请帮忙找出这个问题。我正试图从数据库中得到Hello World,但它不起作用。在我的Windows Power Shell中查看管理窗口。我在Django项目中有一篇应用文章,在那里我修改了模型文件,并制作了一篇标题、日期和正文字段的基本类文章。还有一个功能 STR

    文章模型如下

    from django.db import models
    
    # Create your models here.
    # A MODEL IS REPRESENTED BY CLASS
    
    class Article(models.Model):
        title : models.CharField(max_length=100)
        slug  : models.SlugField()
        body  : models.TextField()
        date  : models.DateTimeField(auto_now_add=True)
        # ADD IN THUMNAILL LETTER
    
        def __str__(self):
            return self.title
    

    命令提示

    Windows PowerShell
    
    >>> from articles.models import Article
    >>> Article
    <class 'articles.models.Article'>
    >>> Article.objects.all()
    <QuerySet [<Article: Article object (1)>, <Article: Article object (2)>]>
    >>> article = Article()
    >>> article
    <Article: Article object (None)>
    >>> article.title = "hello world"
    >>> article.title
    'hello world'
    >>> article.save()
    >>> Article.objects.all()
    <QuerySet [<Article: Article object (1)>, <Article: Article object (2)>, <Article: Article object (3)>]>
    >>> Article.objects.all()[0].title
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    AttributeError: 'Article' object has no attribute 'title'
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   JPG    8 年前

    您的模型定义为 结肠 ( : )集成 等于 ( = )符号。所以你的模型应该是,

    class Article(models.Model):
        title = models.CharField(max_length=100)
        slug = models.SlugField()
        body = models.TextField()
        date = models.DateTimeField(auto_now_add=True)
    
        # ADD IN THUMNAILL LETTER
    
        def __str__(self):
            return self.title


    这是图像参考 ,

    enter image description here



    更新-1

    In [2]: # METHOD -- 1
    
    In [3]: article_1 = Article()
    
    In [4]: article_1.title = "my title 1"
    
    In [5]: article_1.save()
    
    In [6]: Article.objects.all()
    Out[6]: <QuerySet [<Article: my title 1>]>
    
    In [7]: # METHOD -- 2
    
    In [8]: article_2 = Article.objects.create(title="my title 2")
    
    In [9]: Article.objects.all()
    Out[9]: <QuerySet [<Article: my title 1>, <Article: my title 2>]>