Last active
August 4, 2017 23:40
-
-
Save dmitry-saritasa/00c3086ac651b2a44d51393101d8070c to your computer and use it in GitHub Desktop.
proper use of LatLonPoint class in queryset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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