简体   繁体   English

类在django中没有'objects'成员

[英]Class has no 'objects' member in django

from django.http import HttpResponse
from .models import Destination
def index(request):
    boards = Destination.objects.all()
    boards_names = list()
    for Destination in boards:
     boards_names.append(Destination.destinationtext)
     response_html = '<br>'.join(boards_names)
     return HttpResponse(response_html)

I have written this code following just for practice of django framework but I am getting the following errors through pylint : 我只是为了练习django框架编写了这段代码,但是我通过pylint得到了以下错误:

E1101:Class 'Destination' has no 'objects' member
E0601:Using variable 'Destination' before assignment

You have two different issues, and not just one as you say: 你有两个不同的问题,而不只是你说的一个:

E1101:Class 'Destination' has no 'objects' member : Is a warning that occurs because pylint doesn't know about our special Django variables. E1101:Class 'Destination' has no 'objects' member :是因为pylint不知道我们的特殊Django变量而发生的警告 A pylint plugin like pylint-django might do the trick. pylint-django这样的pylint插件可能会成功。

E0601:Using variable 'Destination' before assignment : In the for loop in your code you defined a variable called Destination . E0601:Using variable 'Destination' before assignment :在代码中的for循环中,您定义了一个名为Destination的变量。 This is not only bad practice because python variables need to be in lowercase_underscore but it overrides the Destination class , and that's what is causing this error. 这不仅是不好的做法,因为python变量需要在lowercase_underscore它会覆盖Destination ,这就是导致此错误的原因。 You probably wanted to do something like this: 你可能想做这样的事情:

for d in boards:
# Or:
for destination in boards:

You wrote in your view: 你在视图中写道:

for Destination in boards:
    # ...

This means that Python sees Destination as a local variable, a local variable that you use before it is assigned. 这意味着Python将Destination视为局部变量,即在分配之前使用的局部变量。

You can rename the variable in the loop to solve the problem, but actually you can make it more elegant and faster here by using .values_list(..) : 你可以在循环中重命名变量来解决问题,但实际上你可以通过使用.values_list(..)来使它变得更优雅和更快!

from django.http import HttpResponse
from .models import Destination

def index(request):
    response_html = '<br>'.join(
        Destination.objects.values_list('destinationtext', flat=True)
    )
    return HttpResponse(response_html)

Nevertheless, I'm still not convinced that this solves the matter, since the destinationtext could contain HTML, which then will mix up in the response. 尽管如此,我仍然不相信这解决了这个问题,因为destinationtext可能包含HTML,然后它会在响应中混淆。 Usually it is better to use templates. 通常最好使用模板。

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

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