繁体   English   中英

无法在Django(Python)中向模型/表类添加新功能

[英]Can't add new function to models/table class in django (python)

这是我目前遇到的问题:

  • 我正在使用命令提示符在Windows上浏览第一个Django教程
  • 我在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

你快到了

您需要在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语言:如果“函数”是类的一部分,则称为“方法”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM