0

Hi actually i new to django Restframe work. Here i have mentioned my model My question is that ? I don't know how to store the count of each product. and most viewed product should display in frontend.

MODEL.PY

class Products(models.Model):
   name = models.CharField(max_length=100)
   image = models.CharField(max_length=10, null=True)
   categories =  models.ArrayModelField(
       model_container=Category,
       model_form_class=CategoryForm
   )
   specifications =  models.ArrayModelField(
       model_container=Specifications,
       model_form_class=SpecificationsForm
   )
   description = models.CharField(max_length=500)
   reviews =  models.ArrayModelField(
       model_container=Reviews,
       model_form_class=ReviewsForm
   )
   drizzly = models.BooleanField(default=False)
   complete = models.BooleanField(default=False)
   comment = models.CharField(max_length=500)
   count = models.IntegerField()
ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • inside your view you could call a function which adds 1 to your `count` modelfield each time a user calls the view. But the problem would be that if a user clicks multiple times on a product it would count each click. So to do this properly you would need to save the users ID /IP adress and only add one if the user never viewed the product... – hansTheFranz May 03 '18 at 09:32

3 Answers3

0

If you're using class based views, you can do something like:

Class ProductsDetailView(DetailView):
    model = Products

    def get(self, **kwargs):
        self.object.count += 1
        self.object.save()
        return super(ProductsDetailView, self).get(**kwargs)

To order by count, within your model include

Class Meta:
    ordering = ['count']
HenryM
  • 5,557
  • 7
  • 49
  • 105
0

The best way of doing that is to use atomic operations:

from django.db.models import F

Products.objects.filter(name = name).update(count = F('count')+1)

Note: You have to have a name field set to unique or filter by another unique field.

Chiefir
  • 2,561
  • 1
  • 27
  • 46
0

This works for me:

Class ProductsDetailView(DetailView): model = Products

def get(self, request, *args, **kwargs):       
    object = self.get_object()
    object.count = int(object.count) + 1
    object.save()
    return super(ProductsDetailView, self).get(self, request, *args, **kwargs)