Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add count whenever any entity is fetched Django REST Framework

My model looks like

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

and my urls.py

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

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

Now I wan't to add functionality such that whenever any article is fetched i.e

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

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

so that I can sort them according to this count.

like image 270
Jack Avatar asked Dec 05 '25 15:12

Jack


1 Answers

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.

CODE: First change your model by providing count field a default value, this time its 0.

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',
        default=0
    )

    def __str__(self):
        return self.title

and then do migration.

and then VIEW

class ArticleViewSet(viewsets.ViewSet):

    def retrieve(self, request, pk=None):
        queryset = Article.objects.all()
        fetch = request.GET.get('fetch', False)
        article = get_object_or_404(queryset, pk=pk)
        if fetch:
            article.count += 1
            article.save()
        serializer = ArticleSerializer(article)
        return Response(serializer.data)

and then request with article/1/?fetch=true

you can also do it without fetch flag too,

class ArticleViewSet(viewsets.ViewSet):

    def retrieve(self, request, pk=None):
        queryset = Article.objects.all()
        article = get_object_or_404(queryset, pk=pk)
        article.count += 1
        article.save()
        serializer = ArticleSerializer(article)
        return Response(serializer.data)

now reqeust with article/1/

like image 176
Md. Tanvir Raihan Avatar answered Dec 08 '25 08:12

Md. Tanvir Raihan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!