[英]Django: add additional data in queryset
I've two models: 我有两个型号:
Movie 电影
Attributes : name, plot, rating, release_date, photo 属性 :名称,情节,评级,release_date,照片
Director 导向器
Attributes : name, bio, photo 属性 :名称,生物,照片
Movie and Director models has a many-to-many relationship. 电影和导演模特有多对多的关系。
Now in my movies/views.py
file: 现在在我的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)
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 NB我正在使用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. 是的,有一种不同的方法,不涉及循环和执行N个更多查询以获取相关的控制器对象。
prefetch_related prefetch_related
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类似的目的,因为两者都旨在阻止由访问相关对象引起的数据库查询泛滥,但策略完全不同。
select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. select_related通过创建SQL连接并在SELECT语句中包含相关对象的字段来工作。 For this reason, select_related gets the related objects in the same database query. 因此,select_related在同一数据库查询中获取相关对象。 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. 但是,为了避免加入“多”关系会产生更大的结果集,select_related仅限于单值关系 - 外键和一对一。
prefetch_related, on the other hand, does a separate lookup for each relationship, and does the 'joining' in Python. 另一方面,prefetch_related对每个关系进行单独查找,并在Python中进行“连接”。 This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, 这允许它预取多对多和多对一对象,这是使用select_related无法完成的,
So 所以
Movie.objects.all().prefetch_related('director')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.