如何以键值对格式返回查询结果、添加多查询至响应?现有无外键关联表的电影与制片方关联查询实现方案
Hey there! Let's break down how to solve your problem, plus answer those two technical questions you have. First, let's start with the core task: grouping movies by their production houses, then we'll cover your other queries.
Grouping Movies by Production House
Since your Movie model uses a CharField for production_house (matching the p_name in ProductionHouse—no foreign key link yet), we'll need to manually match those string values to group the data. Here's how to do it:
Quick Implementation (Current Flat Table Setup)
Here's a view function that builds the key-value structure you're looking for:
from django.http import JsonResponse from .models import ProductionHouse, Movie def movies_by_production_house(request): # Grab all production houses first all_production_houses = ProductionHouse.objects.all() final_result = {} for house in all_production_houses: # Fetch all movies where the production_house string matches the house's p_name related_movies = Movie.objects.filter(production_house=house.p_name) # Convert each movie to a dictionary (include all fields you need) movie_dicts = [ { "title": movie.title, "genre": movie.genre, "year": movie.year, "created_at": movie.created_at.isoformat(), "updated_at": movie.updated_at.isoformat(), "creator": movie.creator.username # Adjust based on what creator data you want } for movie in related_movies ] # Add to our result dict with the production house name as the key final_result[house.p_name] = movie_dicts # Return as formatted JSON return JsonResponse(final_result, json_dumps_params={'indent': 4})
This will output exactly the structure you referenced in your examples—each production house name maps to a list of its movies (with all the movie fields you specify).
Better Long-Term Fix: Add a Foreign Key
Your current flat table setup works, but using a foreign key will make queries faster and more maintainable. Here's how to update your Movie model:
class Movie(models.Model): # Replace the CharField with a foreign key linking to ProductionHouse production_house = models.ForeignKey( ProductionHouse, related_name="movies", on_delete=models.CASCADE ) # Keep all your other existing fields title = models.CharField(max_length=100) genre = models.CharField(max_length=100) year = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) creator = models.ForeignKey('auth.User', related_name='movies', on_delete=models.CASCADE)
With this change, querying becomes simpler and more efficient (we'll use prefetch_related to avoid extra database hits):
def movies_by_production_house(request): # Prefetch related movies to optimize performance all_production_houses = ProductionHouse.objects.prefetch_related("movies").all() final_result = {} for house in all_production_houses: # Use the related_name to directly access the house's movies movie_dicts = [ { "title": movie.title, "genre": movie.genre, "year": movie.year, "created_at": movie.created_at.isoformat(), "updated_at": movie.updated_at.isoformat(), "creator": movie.creator.username } for movie in house.movies.all() ] final_result[house.p_name] = movie_dicts return JsonResponse(final_result, json_dumps_params={'indent': 4})
Answering Your Technical Questions
1. How to return results in key-value format?
In Django, it's straightforward:
- Build a standard Python dictionary where your desired keys map to their corresponding values (like production house names → movie lists)
- Use
JsonResponseto convert this dictionary into a JSON response. Django handles the serialization automatically, giving you a proper key-value structure.
If you're working with templates instead of JSON, you can pass the dictionary to your template context and render the key-value pairs directly.
2. How to add multiple query results to a single response?
Just nest all your results inside a single parent dictionary. For example, if you want to return both the grouped movies and a list of production house details, do this:
def combined_results(request): # First query: grouped movies all_production_houses = ProductionHouse.objects.prefetch_related("movies").all() grouped_movies = {} for house in all_production_houses: movie_dicts = [{"title": m.title, "genre": m.genre} for m in house.movies.all()] grouped_movies[house.p_name] = movie_dicts # Second query: production house basic info house_details = [ { "name": house.p_name, "address": house.p_address, "owner": house.owner } for house in all_production_houses ] # Combine both results into one dict combined_response = { "movies_by_house": grouped_movies, "production_house_details": house_details } return JsonResponse(combined_response, json_dumps_params={'indent': 4})
This way, your response includes multiple distinct datasets, each accessible via its own key in the JSON.
内容的提问来源于stack exchange,提问作者p kushwaha

