Реализация системы просмотров | DRF
Я осуществляю систему доски объявлений и встретился с задачей, которая направлена на то, чтобы сортировать объявления на определенной странице по количеству просмотров(от большего к меньшему).
Для этого сначала ввести систему просмотров нужно, но мне в голову не приходит как это можно бы было реализовать.
Моя модель:
class Ad(models.Model):
"""Ad containing information about the product."""
# The author who created the ad, when the author is
# removed from the service, all his ads are deleted.
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True)
# Ad category, if the category corresponding to the ad is deleted, its value is converted to null.
category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
# A short, meaningful name that gives an idea of the product.
name = models.CharField(max_length=80)
# Ad text describing the characteristics of the product being sold.
text = models.TextField(max_length=256)
# The value of the product, which is expressed as a positive numeric value
cost = models.PositiveIntegerField()
# Product currency, as in the case of the category, when it is removed, the field becomes null.
currency = models.ForeignKey(Currency, null=True, on_delete=models.SET_NULL)
# Location of the proposed transaction.
city = models.ForeignKey(City, null=True, on_delete=models.SET_NULL)
# Date of publication of the announcement.
# It is important to understand that this field corresponds to the time zone specified in the settings.
# Among other things, this field is responsible for the time of INSTANCE creation.
pub_date = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-pub_date']
def __str__(self):
return self.name
Вот представление:
class DetailsMixin(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
mixins.DestroyModelMixin, generics.GenericAPIView):
"""Allows you to simplify the code by inheriting the views
that need the listed functionality in this mixin."""
lookup_field = 'id'
queryset = serializer_class = permission_classes = None
def get(self, request, *args, **kwargs):
"""Returns the serialized form of the resulting object."""
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
"""Method for updating the received object."""
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
"""Deleting the received object."""
return self.destroy(request, *args, **kwargs)
class AdDetails(DetailsMixin):
"""Returns a specific ad and information about it.
In addition to all this, author can edit and delete the ad."""
queryset = models.Ad.objects.all()
serializer_class = serializers.AdSerializer
permission_classes = [permissions.IsAuthorOrReadOnly]
Вот, что у меня в идеях:
- Добавить в модель поле views, которое будет определено как PositiveIntegerField.
- Определить в представлении метод dispatch, который будет инкрементировать счетчик.
Вот проблема: нужно как-то ограничить количество просмотров одним пользователем, вместе с этим он должен быть аутентифицированным. Мне неизвестно как. Подскажите, пожалуйста, каким образом можно бы было поступить. Если кто-то сталкивался с такой задачей, каким образом вы с ней справились?