Class has no 'objects' member in django

懵懂的女人 提交于 2019-12-10 09:33:17

问题


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 :

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

回答1:


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. A pylint plugin like pylint-django might do the trick.

E0601:Using variable 'Destination' before assignment: In the for loop in your code you defined a variable called 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. You probably wanted to do something like this:

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



回答2:


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.

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(..):

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. Usually it is better to use templates.



来源:https://stackoverflow.com/questions/51828667/class-has-no-objects-member-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!