Django - TypeError: object of type 'method' has no len()

Django - TypeError: object of type 'method' has no len()

我正在尝试使用一些在线代码将分页器添加到我的网站,但出现此错误 return长度(self.object_list) 类型错误:'method' 类型的对象没有 len()

Views.py

def sample(request):

    WAllPAPER_PER_PAGE = 2
    wallpapers = Wallpaper.objects.all
page = request.GET.get('page', 1)
wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE)
try:
    wallpapers = wallpaper_paginator.page(page)
except EmptyPage:
    wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages)
except:
    wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE)
context = {"wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator}
return render(request, "Wallpaper/sample.html", context )

Models.py

class Wallpaper(models.Model):
    name = models.CharField(max_length=100, null=True)
    size = models.CharField(max_length=50, null=True)
    pub_date = models.DateField('date published', null=True)
    resolution = models.CharField(max_length=100, null=True)
    category = models.ManyToManyField(Category)
    tags = models.ManyToManyField(Tags)
    Device_Choices = [
        ('PC', 'pc'),
        ('mobile', 'mobile')
    ]
    Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC')
    image = models.ImageField(upload_to='Wallpaper/Images/', default="")

    def __str__(self):
        return self.name

你需要调用.all(),否则它是对方法的引用,所以你使用:

#                     call .all() ↓↓
wallpapers = Wallpaper.objects<strong>.all()</strong>

您需要调用它的原因是因为 Paginator 需要可迭代且具有长度的内容,例如列表或 QuerySet