Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

django - 'QuerySet' object has no attribute 'view_count'

Meanwhile using "view count" in my ecommerce project showing this error ('QuerySet' object has no attribute 'view_count')

views.py

class ProductDetailView(TemplateView):
    template_name = 'product-detail-view.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        slug_url = self.kwargs['slug']
        product = Product.objects.filter(slug=slug_url)
        product.view_count += 1
        product.save()
        context["products"] = product
        return context

models.py

class Product(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='products_img')
    wholesale_rate = models.PositiveIntegerField()
    amazon_rate = models.PositiveIntegerField()
    description = models.TextField()
    warranty = models.CharField(max_length=200, null=True, blank=True)
    return_policy = models.CharField(max_length=200, null=True, blank=True)
    view_count = models.PositiveIntegerField(default=0)
question from:https://stackoverflow.com/questions/65873335/queryset-object-has-no-attribute-view-count

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
product = Product.objects.filter(slug=slug_url)

This return a queryset, not an object so you cannot access object field like this. Either use .first() to get an object or if you want to update all objects in queryset, then use

product.update(view_count = F('view_count') + 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...