i need to convert location coordinates to distance and then filter the queryset accordingly using django-filter

Viewed 118

Following is relevant code:

Models.py

class RentTypeChoices(models.IntegerChoices):
        DAILY = 0
        HOURLY = 1
        MONTHLY = 2

rent_type = models.PositiveSmallIntegerField(
    choices=RentTypeChoices.choices)


title = models.CharField(max_length=256)

available_from = models.DateField(default=datetime.date.today)

category = models.ForeignKey(
    Category, related_name="rent_posts", on_delete=models.CASCADE)


price = models.DecimalField(decimal_places=2, max_digits=6)



# Need to convert below location coords to distance
latitude = models.CharField(max_length=120)
longitude = models.CharField(max_length=120)


is_available = models.BooleanField(default=True)

Filters.py

from django_filters import rest_framework as filters
from apps.embla_services.models import RentPost


class RentPostFilters(filters.FilterSet):



    title = filters.CharFilter(lookup_expr="icontains")
    is_available = filters.BooleanFilter()
    rent_type = filters.ChoiceFilter(choices=RentPost.RentTypeChoices.choices)
    category__id = filters.NumberFilter()
    available_from = filters.DateFromToRangeFilter()
    price = filters.RangeFilter()
    # i need to filter this model by distance also
    # search query would contain the min or the maximum distance and i would need to filter 
    # accordingly

    class Meta:
        model = RentPost
        fields = ["title", "is_available",
                  "rent_type", "category", "available_from", "price"]

Views.py

from django_filters import rest_framework as filters
from apps.embla_services.models import RentPost
from apps.embla_services.filters import RentPostFilters  

class SearchRentPosts(generics.ListAPIView):
queryset = RentPost.objects.all()
serializer_class = RentPostBriefSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = RentPostFilters

i know how to convert the location coords between 2 points by using this post Getting distance between two points based on latitude/longitude. however how to exactly use this knowledge to filter the location coordinates to get the distance is my problem.

following the example search request from client side

{{baseUrl}}/rent/search-posts?title=k&rent_type=0&category=14&available_from_after=2022-04-`26&available_from_before=2022-10-05&price_min=40.00&price_max=45.00&distance_max = 5&distance_min=1`

everything else is being done perfectly, only problem is distance part. client need to filter the search results by the distance between his current location and location of the rent post. we would be getting location coords of the client, and we would also have the location coords of the rent post saved

Hope i have explained my question well.

Ps. I haven't added the serializer code as it is not required in this post.

0 Answers
Related