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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With