I've two models:
Movie
Attributes : name, plot, rating, release_date, photo
Director
Attributes : name, bio, photo
Movie and Director models has a many-to-many relationship.
Now in my movies/views.py
file:
def movies_index(request):
movies = Movie.objects.all()
for movie in movies:
movie.directors = movie.directors.all() # tried but in the template it gives me error when accessing by movie.directors
# insert directors in every movie object
context_data = {
'movies': movies
}
return render(request, 'movies/index.html', context_data)
I want to insert directors data in to every movie object. So that the result may be like:
[
{
name: "12 Angry Man",
plot: "bla",
release_date: "1-2132",
directors: [
{
name: "Quentine",
bio: "Lodfs"
},
{
name: "Tarantino",
bio: "Lodsdfs"
}
]
}
]
How can I achieve this?
Or, is there any different approach do do this?
NB I'm using Django 1.9, Python 2.7
Yes, there is a different approach that does not involve looping and executing N more queries to fetch the related director objects.
has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.
select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a 'many' relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.
prefetch_related, on the other hand, does a separate lookup for each relationship, and does the 'joining' in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related,
So
Movie.objects.all().prefetch_related('director')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.