Home > Software engineering >  TypeError at /check 'ModelBase' object is not iterable in django
TypeError at /check 'ModelBase' object is not iterable in django

Time:12-10

I am trying to print data from database in command prompt(terminal) when i run program it gives error showing TypeError at /check 'ModelBase' object is not iterable i dont understand what the proble is please help me to solve it.

this is my views.py here the table name is dish and i want to print name of that dish `

def check(request):
    dishs = dish.objects.all()
    for dishs in dish:
        print(dishs.dish_name)
    params = {'dish': dishs}
    return render(request, "card/check.html", params)

this is my urls.py

urlpatterns = [
    path('index', views.index, name="index"),
    path('check', views.check, name="check"),
    path('delete/<int:id>', views.delete, name='delete'),
    path('update/<int:id>', views.update, name='update'),
] static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

this is my models.py

class dish(models.Model):
    dish_id = models.AutoField
    dish_name = models.CharField(max_length=255, blank=True, null=True)
    dish_category = models.CharField(max_length=255, blank=True, null=True)
    dish_size = models.CharField(max_length=7, blank=True, null=True)
    dish_price = models.IntegerField(blank=True, null=True)
    dish_description = models.CharField(max_length=255, blank=True, null=True)
    dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) 
    dish_date = models.DateField()

    def __str__(self):
        return self.dish_name

`

CodePudding user response:

You are using queryset object to fetch class's attribute. It needs an instance to use class's attribute. Just change your check method to the following:

def check(request):
    dishs = dish.objects.all()
    for dish in dishs:
        print(dish.dish_name)
    params = {'dish': dishs}
    return render(request, 
    "card/check.html", params)
  • Related