Search code examples
djangopostgisgeodjango

GeoDjango, distance filter based on database column taking into account the radius of both the seeker and the one he is looking for


I need to find objects taking into account the radius of both the seeker and the one he is looking for. How i can do this?

At now i can filter from seeker side:

n_range = Obj.objects.filter(location__distance_lt=(
                       obj.location, Distance(mi=obj.radius)
                    )
                )

This is my model:

class Obj(models.Model):
    RADIUS_CHOICES = [
        (1, "1 km round"),
        (2, "2 km round"),
        (3, "3 km round"),
    ]
    radius = models.PositiveIntegerField(
        default=RADIUS_CHOICES[0][0],
        choices=RADIUS_CHOICES
    )
  location = models.PointField(null=True, blank=True)

It is necessary that in the end result there should be only those objects that fall into the radius of the seeker, and at the same time, the seeker must fall into the radius of those whom he seeks


Solution

  • from django.contrib.gis.measure import D
    from django.contrib.gis.db.models.functions import Distance
    
    obj = Obj.objects.get(id=1)
    in_rande = Obj.objects.filter(
        location__distance_lte=(
            obj.location, D(mi=obj.radius)
        )).annotate(
            distance=Distance('location', profile.location)
        ).values('id', 'distance', 'radius')
    relevant_ids = [i['id'] for i in in_rande if i['radius'] > i['distance'].km]