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

基于Django 2.0编写复杂查询的技术咨询(附Recommender模型)

Hey there! Let's dive into some practical complex query implementations for your Recommender model using Django's ORM. I'll cover common real-world scenarios you might need, with clear, reusable code snippets:

Common Complex Query Scenarios & Implementations

If you need to pull all approved recommendations for a specific brand, and want to avoid performance issues from repeated database hits (N+1 problem), use select_related to prefetch related user and state data:

from django.contrib.auth import get_user_model
from your_app.models import Recommender

# Get the target brand user (replace with your lookup logic)
BrandUser = get_user_model()
target_brand = BrandUser.objects.get(username="acme_brand")

# Query with prefetching related objects
approved_recommendations = Recommender.objects.filter(
    brand=target_brand,
    authorized__id=6  # Match your "approved" State ID
).select_related("customer", "recommender", "authorized")

# Iterate through results without extra DB calls
for reco in approved_recommendations:
    print(f"Customer: {reco.customer.email}, Recommender: {reco.recommender.username}, Status: {reco.authorized.name}")

2. Recent Pending Recommendations (Sorted by Date)

To get all pending recommendations created in the last 7 days, sorted from newest to oldest:

from datetime import datetime, timedelta

# Calculate the cutoff date
seven_days_ago = datetime.now() - timedelta(days=7)

recent_pending_reco = Recommender.objects.filter(
    authorized__id=5,  # Match your "pending" State ID
    dateTime__gte=seven_days_ago
).order_by("-dateTime")  # Descending order (newest first)

3. Aggregate Recommendation Counts by Status & Recommender

If you need to generate stats—like how many recommendations each user has made, broken down by status—use annotate and values for aggregation:

from django.db.models import Count

recommender_status_stats = Recommender.objects.values(
    "recommender__username", "authorized__name"
).annotate(
    total_recommendations=Count("id")
).order_by("recommender__username", "authorized__name")

# Print aggregated results
for stat in recommender_status_stats:
    print(f"Recommender: {stat['recommender__username']} | Status: {stat['authorized__name']} | Count: {stat['total_recommendations']}")

To identify customers who've been recommended more than once by the same recommender:

repeat_recommendations = Recommender.objects.values(
    "customer__username", "recommender__username"
).annotate(
    recommendation_count=Count("id")
).filter(recommendation_count__gt=1)

for entry in repeat_recommendations:
    print(f"Customer {entry['customer__username']} was recommended {entry['recommendation_count']} times by {entry['recommender__username']}")

If you have a specific complex query in mind—like cross-model filtering, subqueries, or advanced aggregations—just share the exact requirement and I can refine the solution further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:08:25