DEV Community


Posted on


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


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()
        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'])
def getSingleNews(request,title):
        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():
        serializer = NewsSerializer(obj)
        return Response(,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.

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

Enter fullscreen mode Exit fullscreen mode

Full code in file -->

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git