Django环境下借助Djongo读取MongoDB集合的方法咨询
Hey there! Your approach using Djongo is totally on the right track—let me break this down clearly and add some details to make sure you get it working smoothly.
1. First, Lock in the Setup & Installation
- Start by installing Djongo via pip if you haven’t already:
pip install djongo - Update your Django project’s
settings.pyto replace the default database backend with Djongo. Here’s a sample config:DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'your_mongodb_database_name', 'CLIENT': { 'host': 'mongodb://localhost:27017/', # Use your remote URI if MongoDB isn't local # Add these lines if your DB requires authentication: # 'username': 'your_db_username', # 'password': 'your_db_password', } } }
2. Creating Models for Your Collections
You’re spot-on that you only need to define fields you want to interact with—no need to map every single field in your MongoDB documents. Just make sure field names match exactly (MongoDB is case-sensitive!).
Example Model for airports
from django.db import models class Airport(models.Model): # Map to your MongoDB field names—use db_column if the Django name differs name = models.CharField(max_length=255, db_column='name_airports') iata_code = models.CharField(max_length=3, null=True) city = models.CharField(max_length=255, null=True) class Meta: db_table = 'airports' # Explicitly link to your MongoDB collection name
Example Model for routes
class Route(models.Model): origin_airport = models.CharField(max_length=3) destination_airport = models.CharField(max_length=3) airline = models.CharField(max_length=255, null=True) class Meta: db_table = 'routes'
Pro tip: If your MongoDB docs have nested fields, use Django’s
JSONFieldto handle them. For example, a nestedlocationfield with lat/lon can be defined aslocation = models.JSONField(), and queried likeAirport.objects.filter(location__lat__gte=10.0).
3. Querying Data (Your Example is 100% Correct!)
The Django ORM syntax you mentioned works exactly as expected with Djongo. Here are a few more examples to expand on it:
# Your original query to get airports starting with 'Goro' goro_airports = Airport.objects.filter(name__startswith='Goro') # Get all routes from a specific airport nyc_routes = Route.objects.filter(origin_airport='JFK') # Get a single airport by IATA code (use get() for unique results) lax_airport = Airport.objects.get(iata_code='LAX')
Djongo translates these Django ORM calls into native MongoDB queries behind the scenes, so you can use all the standard ORM methods you’re familiar with.
4. Handy Extra: Raw MongoDB Queries
For complex operations that don’t fit neatly into the Django ORM (like aggregations or advanced filters), you can run raw MongoDB queries directly:
from djongo.models import QuerySet # Raw query to match airports with names containing 'Goro' (case-insensitive) raw_query = {"name_airports": {"$regex": "Goro", "$options": "i"}} matching_airports = Airport.objects.raw(raw_query)
5. Quick Workflow Check
Don’t forget to run these commands after defining your models—even though MongoDB is schema-less, Django uses migrations to track model changes:
python manage.py makemigrations python manage.py migrate
内容的提问来源于stack exchange,提问作者christianbueno.1

