In today’s world, location-based features are increasingly important in web applications. Integrating geographic data can significantly enhance the user experience, whether it's finding nearby friends, locating nearby services, or enabling geotagged content.
This article will explore how to use Django’s ORM to find nearby users based on their geographic coordinates (latitude and longitude) and a specified radius.
First, we will define a Location model to store the geographical coordinates of each user. We'll use Django's built-in User model to associate each location with a user.
from django.db import models from django.contrib.auth.models import User class Location(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6, db_index=True) longitude = models.DecimalField(max_digits=9, decimal_places=6, db_index=True) def __str__(self): return str(self.user)
user: A foreign key pointing to the Django User model. This establishes a relationship where each user can have one or more locations. latitude & longitude: DecimalField field used to store geographic coordinates with an accuracy of up to six decimal places, which is sufficient for most location-based applications.
Implement Haversine formula in Django
Haversine's formula is a widely used mathematical formula for calculating the spherical distance between two points on the Earth's surface, using latitude and longitude. This formula is particularly useful in navigation, geofencing, geospatial analysis, and location-based services.
Here is a function integrating the Haversine formula into the Location model to get users within a specified radius using the Django ORM:
from django.db.models import F, Value from django.db.models.functions import ACos, Cos, Radians, Sin class Location(models.Model): # ... [字段如上] ... @classmethod def get_users_within_radius(cls, center_latitude, center_longitude, radius_km): # Haversine 公式计算距离 distance_expression = ( ACos( Sin(Radians(F('latitude'))) * Sin(Radians(Value(center_latitude))) + Cos(Radians(F('latitude'))) * Cos(Radians(Value(center_latitude))) * Cos(Radians(F('longitude')) - Radians(Value(center_longitude))) ) * 6371 # 地球半径(公里) ) # 过滤指定半径内的用户 users_within_radius = cls.objects.annotate( distance=distance_expression ).filter( distance__lte=radius_km ).select_related('user') return users_within_radius
This method uses the Haversine formula to calculate distance and filter users within a given radius.
Get users within a specified radius
With the get_users_within_radius
method, getting nearby users is easy. Here's how to use it:
from .models import Location # 加德满都的纬度和经度 center_latitude = 27.707460 center_longitude = 85.312205 radius_km = 10 # 10 公里 nearby_location_points = Location.get_users_within_radius( center_latitude, center_longitude, radius_km ) nearby_users = [ location.user for location in nearby_location_points ]
Explanation
-
Define center coordinates: Replace
center_latitude
andcenter_longitude
with the desired center point, such as the current user's location. -
Radius specification: Set
radius_km
to the desired search radius in kilometers. -
Get nearby locations: Call
get_users_within_radius
to retrieve Location instances within a specified radius. - Extract users: Iterate over Location instances to collect associated User objects.
Implementing geolocation search in Django is a valuable skill for developers aiming to create location-based services. By understanding Haversine's formula, developers can build efficient location-based searches.
For more advanced geographic functionality, explore GeoDjango and spatial databases.
The above is the detailed content of Django: Find Nearby Users with Coordinates and Radius. For more information, please follow other related articles on the PHP Chinese website!

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool