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
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)
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
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)
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
Top comments (0)