Skip to main content
 首页 » 编程设计

python之Django model.foreignKey 并返回 self.text 错误

2025年05月04日34开发

所以我在 Django 中处理 model.py,我遇到了 2 个 pylint 错误。 我不明白为什么?这是 pylint 的问题还是我在代码中做错了什么。

E1120:No value for argument 'on_delete' in constructor call     
E1136:Value 'self.text' is unsubscriptable 
  • 第一个在 Entry 中的第 19 行 topic = models.ForeignKey(主题)

  • 第二个在第 24 行 self.text[:50]

如果我删除入口类,代码就可以工作

from django.db import models 
 
# Create your models here. 
class Topic(models.Model): 
"""A topic the user is learning about""" 
text = models.CharField(max_length=200) 
date_added = models.DateTimeField(auto_now_add=True) 
 
def __str__(self): 
    """Return a string representation of the model.""" 
    return self.text 
 
class Entry(models.Model): 
"""Something specific learned about a topic""" 
topic = models.ForeignKey(Topic) 
text = models.TextField() 
date_added = models.DateTimeField(auto_now_add=True) 
 
class Meta: 
    verbose_name_plural = "entries" 
 
def __str__(self): 
    """Return a string representation of the model.""" 
    return self.text[:50] + "..." 

请您参考如下方法:

问题是 Django 1.9 中的 ForeignKey 在 Django 2.0 中需要 1 个位置参数 ForeignKey 2 需要位置参数

  topic = models.ForeignKey("Topic", on_delete=models.PROTECT)