如何在django中找到附近的物体?

问题描述 投票:0回答:1

我有一个服务提供商模型。它有两个名为:lat 和 lon

的字段
class Provider(models.Model):
    name = models.CharField(max_length=100)
    lat = models.CharField(max_length=20)
    lon = models.CharField(max_length=20)
    address = models.TextField(null=True , blank=True)

    def save(self, *args, **kwargs):
        try:
            data = getaddress(self.lat , self.lon)
            self.address = data['formatted_address']
        except:
            pass
        super(Provider, self).save(*args, **kwargs)

我如何从用户那里获取位置并找到离我的用户较近的一些服务提供商? 它必须来自纬度和经度字段,因为服务提供商可能位于另一个城市! 处理速度也很重要!

python django django-models django-rest-framework django-views
1个回答
0
投票

阿里雷萨! 我对如何解决你的问题有一个可行的想法。 所以,我通过 geoip2 库看到了一个解决方案。

在这里您可以找到有关在 django 中使用此库的信息。 来自 django 文档

这是一篇关于相关问题的有趣的文章。这可能会有帮助。 我还发现了一些已经讨论过的类似问题。可能对你有用。 所以。如果短路,解决方法如下:

# Let's assume that you have already created a django project and an application from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() # You`ll need to user IP. For example it possible to get this via some way like that: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip # After that put response of that function to fallowing: g.city("72.14.207.99") {'accuracy_radius': 1000, 'city': 'Mountain View', 'continent_code': 'NA', 'continent_name': 'North America', 'country_code': 'US', 'country_name': 'United States', 'is_in_european_union': False, 'latitude': 37.419200897216797, 'longitude': -122.05740356445312, 'metro_code': 807, 'postal_code': '94043', 'region_code': 'CA', 'region_name': 'California', 'time_zone': 'America/Los_Angeles', 'dma_code': 807, 'region': 'CA'}

可以看到响应中有纬度和经度。接下来,您只需将接收到的宽度和经度与提供者的宽度和经度进行比较。例如,您可以连接 django-filter 模块并发出按宽度和经度字段过滤的请求。

希望我的回答对你有一点帮助。

© www.soinside.com 2019 - 2024. All rights reserved.