我有兩個型號:Django的:添加額外的數據查詢集
電影
屬性:名字,情節,等級,RELEASE_DATE,照片
主任
屬性:名稱,生物,照片
電影和導演模特有多對多的關係。
現在在我的movies/views.py
文件:
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)
我想在每一個影片對象插入董事的數據。所以結果可能如下:
[
{
name: "12 Angry Man",
plot: "bla",
release_date: "1-2132",
directors: [
{
name: "Quentine",
bio: "Lodfs"
},
{
name: "Tarantino",
bio: "Lodsdfs"
}
]
}
]
我該如何實現這個目標?
或者,有沒有不同的方法做到這一點?
N.B.我正在使用Django 1.9,Python 2.7
如果我這樣做'Movie.objects.all ().prefetch_related('Directors')',我怎樣才能得到模板文件中的電影導演? – Emu
這是一個不同的問題。如果您遇到問題,請使用您的模板發佈另一個模板。 – e4c5
明白了我自己。不管怎麼說,還是要謝謝你。 – Emu