DEV Community

sium_hossain
sium_hossain

Posted on

7 3

Unique view count in specific object/view django rest framework

First of all we have to create a data table for storing all IP address like this -



class IpAddress(models.Model):
    ip = models.CharField(max_length=255)

    def __str__(self):
        return self.ip


Enter fullscreen mode Exit fullscreen mode

Then we have to store all unique IP address beside our specific object or view (blog, article, post etc)



views = models.ManyToManyField(IpAddress,blank=True)


Enter fullscreen mode Exit fullscreen mode

demo

Then we have to extract IP address by passing request in a function and save this IP address into specific object or view

Here is the function which gives us the IP address



def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


Enter fullscreen mode Exit fullscreen mode

And now in our specific view we will pass the request and check extracted IP address already exist in our database table or not. If exist we will save this inside view field or if extracted IP address doesn't match with previous dataset -> we will store new IP address into IP address table and store it as well as inside view field



 @swagger_auto_schema(tags=['Get a single news'],methods=['get'])
@api_view(['GET'])
def getSingleNews(request,title):
    try:
        obj = News.objects.get(title=title)
    except News.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        ip = get_client_ip(request)
        if IpAddress.objects.filter(ip=ip).exists():
            obj.views.add(IpAddress.objects.get(ip=ip))
        else:
            IpAddress.objects.create(ip=ip)
            obj.views.add(IpAddress.objects.get(ip=ip))
        serializer = NewsSerializer(obj)
        return Response(serializer.data,status=status.HTTP_200_OK)


Enter fullscreen mode Exit fullscreen mode

And now we can declare a method inside serializer and pass our desire view count number.
In serializers.py



views = serializers.SerializerMethodField()
def get_views(self,obj):
        count = obj.views.count()
        return count



Enter fullscreen mode Exit fullscreen mode

Full code in seralizers.py file -->
demo

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs