You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

Using Djongo to Access MongoDB Collections in Django

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.py to 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 JSONField to handle them. For example, a nested location field with lat/lon can be defined as location = models.JSONField(), and queried like Airport.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:32:03