每当获取任何实体时都增加计数Django REST Framework

我的模特看起来像

class Article(models.Model):
    article_type = models.ForeignKey(
        ArticleType,
        on_delete=models.CASCADE,
        related_name='articles'
    )

    title = models.CharField(
        max_length=100,
        verbose_name='Article Title'
    )

    count = models.IntegerField(
        verbose_name='Frequency Count'
    )

    def __str__(self):
        return self.title

和我的urls.py

router = DefaultRouter()
router.register('article', ArticleViewSet, basename='article')

urlpatterns = [
    path('viewset/', include(router.urls)),
]

现在,我不想添加功能,以便每当获取任何文章即

http://127.0.0.1:8000/viewset/article/{pk}

than 'count' of article of id=pk becomes count = count+1

这样我就可以根据此计数对其进行排序。

评论
ut_quo
ut_quo

This can be achieved by sending a request like fetch=true or seen=true from client side whenever the api been fetched by the client i.e the client will sent you fetch=true whenever fetch the api and from backend you have to catch that flag and have to check if fetch=true and increase instance.count += 1 and save the change in your model.

点赞
评论