Home > OS >  How to fetch integer values from the Django objects?
How to fetch integer values from the Django objects?

Time:03-27

I already created integerField for saving data in the model. But showing the bellow error. How can I convert a string list into an integer list?

Django Model:

class Frontend_Rating(models.Model):
    Rating = models.IntegerField( null=True)

Views:

#index

def index(request):
    
    frontend_all_ratings = Frontend_Rating.objects.all()
    number_of_frontend_rating = frontend_all_ratings.count()

    frontend_rating_list = []
    total_ratings = 0
    for frontend_rating_item in frontend_all_ratings:
        frontend_rating = int(frontend_rating_item.Rating)
        frontend_rating_list.append(frontend_rating)
        
        total_ratings = total_ratings frontend_rating_list[frontend_rating_item]


    context = {
        "number_of_frontend_rating":number_of_frontend_rating,
        "frontend_rating_list":frontend_rating_list,
        "total_ratings":total_ratings
        
    }
    return render(request,'0_index.html',context)

Erorr:

TypeError at /
list indices must be integers or slices, not Frontend_Rating
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.2.3
Exception Type: TypeError
Exception Value:    
list indices must be integers or slices, not Frontend_Rating
Exception Location: D:\1_WebDevelopment\Business_Website\business_app\views.py, line 33, in index
Python Executable:  C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.5

CodePudding user response:

Your error is on this line:

total_ratings = total_ratings frontend_rating_list[frontend_rating_item]

frontend_rating_item is an instance of Frontend_Rating.

I think it should be:

frontend_rating_list = []
total_ratings = 0
for frontend_rating_item in frontend_all_ratings:
    frontend_rating = frontend_rating_item.Rating
    frontend_rating_list.append(frontend_rating)

    if frontend_rating:
        total_ratings  = frontend_rating
  • Related