【问题标题】:Can't add new function to models/table class in django (python)无法在 django(python)中的模型/表类中添加新函数
【发布时间】:2014-10-14 22:33:48
【问题描述】:

这是我目前遇到的问题:

  • 我正在使用命令提示符在 Windows 上运行 the first django tutorial
  • 我在 models.py 中创建了一个名为“问题”的表。
  • 我正在尝试在此类中创建 __str__() 函数,如下所示:

.

from django.db import models
class Question(models.Model):
   def __str__(self):
     return self.question_text`

这就是我的 models.py 的样子:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

我收到的错误如下:

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 117, in __new__
kwargs = {"app_label": package_components[app_label_index]}
IndexError: list index out of range

有人知道吗?我是 django 的菜鸟,我不能 100% 确定 base.py 应该在这里做什么。

Base.py 可以在这里找到:https://github.com/django/django/blob/master/django/db/models/base.py

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    你快到了

    您需要在 models.py 文件中的 Question 类中添加 def __str__() 方法。

    您的 models.py 应该如下所示:

    from django.db import models
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        def __str__(self):
            return self.question_text
    class Choice(models.Model):
        question = models.ForeignKey(Question)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
        def __str__(self):
            return self.choice_text #or whatever u want here, i just guessed u wanted choice text
    

    您实际上在做的是在您子类化的类中覆盖内置的 dunder 方法。 models.Model 本身已经有一个 __str__ 方法,而您只是在 Question 版本的 models.Model 中修改它的行为

    PS。如果你在 python 2 上,方法名称应该是 __unicode__ 而不是 __str__

    PPS。一点点 OOP 语言:如果“函数”是类的一部分,则称为“方法”

    【讨论】:

    • 它发生了,请查看this 关于子类化/继承的文章,因为这通常有助于了解您为什么要做某事以了解它为什么不起作用
    猜你喜欢
    • 2018-10-16
    • 2021-10-06
    • 2014-07-24
    • 1970-01-01
    • 2014-10-17
    • 2023-03-15
    • 2018-07-18
    • 2012-11-15
    • 2020-04-20
    相关资源
    最近更新 更多