I have a models named Restaurant ,i want to fetch all the restaurant within the 3km radius of user's current location.
I am posting the model and views.
models.py
class Restaurant(models.Model):
restaurant_owner = models.ForeignKey(Account, on_delete=models.CASCADE,
related_name="restarant_details",
null=True, blank=True)
latitude = models.CharField('Latitude', max_length=30, blank=True, null=True)
longitude = models.CharField('Longitude', max_length=30, blank=True, null=True)
location = models.PointField(blank=True, null=True)
owner_name = models.CharField(max_length=200,null=True,blank=True)
restaurant_name = models.CharField(max_length=200,null=True,blank=True)
registration_no = models.CharField(max_length=200,null=True)
registration_date = models.DateField()
registration_mobile = models.CharField(max_length=200,null=True)
VIEWS.PY
class RestView(viewsets.ViewSet):
permission_classes = [IsAuthenticated,OnlyUser]
def list(self, request):
try:
radius = 2
print(self.request)
user_location=request.user.location
print(user_location)
if not user_location:
return Response({"message": "User is not Available","success":False},status=status.HTTP_400_BAD_REQUEST)
#query_set=Restaurant.objects.annotate(distance=Distance('restaurant_owner__location',user_location)).order_by('-distance')
#query_set=Restaurant.objects.filter(location__distance_lt=(user_location, Distance(km=radius)))
#query_set=Restaurant.objects.filter(restaurant_owner__location__dwithin=(user_location, Distance(mi=90)))
#query_set=Restaurant.objects.filter(location__distance_lt=(user_location,Distance(m=5000)))
#query_set=Restaurant.gis.filter(location__dwithin=(user_location, 0.008))
# max_distance = 10000 # distance in meter
# buffer_width = max_distance / 40000000. * 360. / math.cos(point.y / 360. * math.pi)
# buffered_point = point.buffer(buffer_width)
# query_set=Restaurant.objects.filter(location__distance__lte=(user_location, D(m=max_distance)),location__overlaps=buffered_point)
query_set=Restaurant.objects.filter(location__distance__lt=(user_location,Distance(km=radius)))
serializer=RestaurantSerializer(data=query_set,many=True,context={'request': self.request})
serializer.is_valid()
serializer.save()
return Response({"message": serializer.data,"success":True},status=status.HTTP_200_OK)
except Exception as e:
traceback.print_exc()
return Response({"message": str(e),"success":False,},status=status.HTTP_200_OK)
I found interesting answer here answer here(SO) but not exactly 100% correct i think.
One of the best option is convert the raidus into degree and then differentiate that. Take a look on this and let me know if its helped.