Skip to content

Instantly share code, notes, and snippets.

@dmitry-saritasa
Last active August 4, 2017 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitry-saritasa/00c3086ac651b2a44d51393101d8070c to your computer and use it in GitHub Desktop.
Save dmitry-saritasa/00c3086ac651b2a44d51393101d8070c to your computer and use it in GitHub Desktop.
proper use of LatLonPoint class in queryset
class PopularityDistanceQuerySetMixin(object):
"""Mixin when you need to add popularity, distance,
nearby calls to queryset, can be used as it for Coupon
and Merchant models
"""
def with_popularity(self):
"""Adds counted field popularity which is the value
of redeemed coupon
"""
return self.annotate(
popularity=models.Count(
models.Case(
models.When(
couponstat__action='R',
then=1,
)
),
)
)
def distance(self, latitude, longitude):
"""Add distance information to merchant based on nearest
place associated with the merchant
"""
point = GEOSGeometry("SRID=4326;POINT ({lon} {lat})".format(
lat=latitude, lon=longitude))
return self.annotate(distance=models.Min(
Distance('places__location', point)))
def nearby(self, latitude, longitude, proximity=None):
"""Get nearby coupons.
Custom queryset method for getting coupons for nearby places.
Returns:
A queryset of ``Coupon`` objects.
"""
proximity = proximity or getattr(config, 'PROXIMITY')
if proximity:
point = LatLonPoint(latitude=latitude, longitude=longitude)
# we query for location nearby for places first and then
# annotate with distance to the same place
return self.filter(
places__location__distance_lte=(point, D(ft=proximity))).\
annotate(distance=models.Min(Distance(
'places__location', point)))
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment