查询适用于 shell 但不适用于 Django 程序代码

Querying works on shell but not on the Django program code

我是 python 和 Django 的新手。

我已经尝试了几种在堆栈溢出时找到的解决方案,但我仍然遇到同样的问题。我试过从 shell 查询,它运行良好,但不是在我的代码上。

我使用

安装了 pylint
pip install pylint-django

我还在 设置 > 用户设置 > Python 上将 Linter 设置pyLint 更改为pylint_djangoflake8,但没有积极的结果。 我仍然收到消息 "Class Courses has no 'objects' member pylint(no-member)"

这些是我来自 models.py 的代码:

class Courses(models.Model):
course_title = models.CharField(max_length=200)
course_image = models.ImageField(upload_to='course_images/')
course_duration = models.TimeField() 

 def __str__(self):
 return self.course_title

views.py 看起来像这样:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Courses

def homepage(request):
    cos = Courses.objects.all()
    context={ 'courses': cos }

    return render(request, "main/home.html", context) 

我需要帮助。我完全卡住了。

这是来自 linter 的错误消息,而不是来自库的错误消息。你不必为此担心。由于 IDE 可能应用了默认的 linter 设置,这可能是造成这种情况的原因。此外,作为一种做法,您可以为您的模型保留单一名称,如果您在管理员中注册该模型,它最后会自动给出一个 s

应该是这样的

from django.db impot models

class Courses(models.Model):
    course_title = models.CharField(max_length=200)
    course_image = models.ImageField(upload_to='course_images/')
    course_duration = models.TimeField()

    def __str__(self):
        return self.course_title

它一直就在我眼皮子底下。

转到 设置 > 搜索 "terminal" > 打开任何 "Edit in settings.json" 并添加下面的代码。

"python.linting.pylintArgs": ["--load-plugins=pylint_django"]

注意: 确保在添加下面的代码之前在最后一行的末尾添加逗号,否则会出错。

保存然后返回设置并搜索 "lint" 检查搜索的 左侧 并找到 Python Configuration

确保 "The Linter to use" 设置为 pyLintpylint_django

那应该没问题。