Reputation: 7310
Let's say that I have a photo model. In the photo model, I have longitude and latitude fields in my photo model.
class Photo(models.Model):
photographer = models.ForeignKey(Photographer, related_name = 'shot_owner')
title = models.CharField(max_length=140, blank=True)
description = models.CharField(max_length, blank=True)
longitude = models.DecimalField(max_digits=16, decimal_places = 14, null=True, blank=True)
latitude = models.DecimalField(max_digits=16, decimal_places = 14, null=True, blank=True)
I use Django Tastypie as my rest framework. Let's say a user decides they'd like to see all the photos within a 10 km radius. How can one achieve this? Here is my resource below:
class PhotosNearMe(ModelResource):
photographer = fields.ForeignKey(PhotographerResource, 'photographer', full=True)
class Meta:
queryset = Photo.objects.all()
resource_name = 'photos-near-me'
fields = ['id', 'title', 'description', 'latitude','longitude','photographer']
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
include_resource_uri = False
filtering = {
'photographer' : ALL_WITH_RELATIONS,
}
def get_object_list(self, request):
return super(PhotosNearMe, self).get_object_list(request).filter(....)
This is where I am having trouble. As I mentioned before, the user will be able to send me their coordinates and I can save them. Something like:
lati = bundle.obj.latitude
longi = bundle.obj.longitude
I can later use lat and long to filter through all the images in the database that are within a 10 km radius. The question is, how? am I suppose to filter by some sort of range?
EDIT**
I have found something that I could perhaps use, Find items within a certain range of given coordinate
Is there anyway I can implement this?
Upvotes: 4
Views: 5225
Reputation: 1890
If you are going to be handling a lot of data that is geographic in nature, you may consider GeoDjango, which has support for spatial lookups. However, it only works with certain backends, so it may require a lot more to get set up if your stack doesn't meet the requirements.
Otherwise, the other option would be to do a little geometry and calculate the bounding circle around your point, and filter on that. Here's an example, and it looks like there are plenty of other writeups on how to do this.
EDIT: in response to your question on how to do this, I am assuming you mean the second part. I am not an expert in TastyPie, but it looks like you will have to this in your view:
It seems like all of these would belong in ModelResource.build_filters.
Upvotes: 9