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

Django集成PyMongo连接MongoDB后数据更新仍返回重复响应问题

Hey there! Let's figure out why your Django + PyMongo setup is returning stale data—this is a super common gotcha, so I’ve got a few fixes to walk you through:

1. Check for Django View Caching

First up, take a look at your view functions (like homepage or registe). If you’re using the @cache_page decorator, that’s almost certainly the culprit. Django will cache the entire response of that view, so even if your MongoDB data updates, the old cached page gets returned.

Fix: Remove the decorator if you don’t need caching for that view, or adjust the cache timeout if you can tolerate some delay. Example:

# 🔴 Bad: Caches the view response indefinitely (or for set timeout)
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)  # Caches for 15 minutes
def homepage(request):
    # ... your code ...

# 🟢 Good: No caching for dynamic data
def homepage(request):
    # Query MongoDB INSIDE the view, every time
    db = client['your_db']
    data = db['your_collection'].find()
    return render(request, 'home.html', {'data': data})

2. Avoid Global Query Variables

If you’ve defined your PyMongo queries outside of your view functions (like at the top of your views.py), those results only get fetched once when the server starts—so every subsequent request uses that stale initial data.

Fix: Move all database queries inside your view functions, so they run fresh on every request:

# 🔴 Bad: Global query runs once at server start
client = pymongo.MongoClient('your_connection_string')
db = client['your_db']
stale_data = db['your_collection'].find()

def homepage(request):
    return render(request, 'home.html', {'data': stale_data})

# 🟢 Good: Query runs on every request
def homepage(request):
    client = pymongo.MongoClient('your_connection_string')  # Or reuse client properly
    db = client['your_db']
    fresh_data = db['your_collection'].find()
    return render(request, 'home.html', {'data': fresh_data})

(Pro tip: Reusing the MongoClient instance is better than creating a new one every time—you can initialize it once in a separate module and import it, but make sure queries happen inside the view.)

3. Check Django’s Global Cache Middleware

If you’ve added cache middleware to your settings.py, your entire site might be caching responses. Look for these lines in MIDDLEWARE:

MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',
    # ... other middleware ...
    'django.middleware.cache.FetchFromCacheMiddleware',
]

Fix: Remove these middleware classes if you don’t need site-wide caching, or use django.views.decorators.cache.never_cache to exclude specific views:

from django.views.decorators.cache import never_cache

@never_cache
def registe(request):
    # Your registration logic with email checks here
    email = request.POST.get('email')
    exists = db['users'].find_one({'email': email}) is not None
    # ... rest of your code ...

4. Verify Email Check Logic

For your email comparison issue, make sure you’re querying the database every time you perform the check—not using a cached list of emails. If you’re storing emails in a global variable or reusing a cursor from an earlier query, you’ll always get the same result.

Example of fresh email check:

def registe(request):
    if request.method == 'POST':
        user_email = request.POST['email']
        # Query MongoDB directly for this email, every time the form is submitted
        db = client['your_db']
        existing_user = db['users'].find_one({'email': user_email})
        if existing_user:
            return HttpResponse("Email already exists!")
        else:
            # Create new user
            db['users'].insert_one({'email': user_email})
            return HttpResponse("Registration successful!")
    return render(request, 'register.html')

Give these steps a try—most likely it’s one of the caching issues above causing your stale data. Let me know if you need more help with specific parts of your code!

内容的提问来源于stack exchange,提问作者Praneeth Karnena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:20:19