所有的价值观许多到很多领域:Django [英] All the values of the many to many field : Django
本文介绍了所有的价值观许多到很多领域:Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型:
class Author(models.Model);
name = models.CharField(max_length=255)
class Book(models.Model):
title = models.CharField(max_length=255)
authors = models.ManyToManyField(Author, null=True, blank=True)
现在,我想要的信息所有的书。所以,我做了:
Now, I want the info of all the books. So, I did:
book_info = Book.objects.all().values('title', 'authors__name')
而且,它给出一个输出(对于1本有2个作者的书):
And, it gives an output like (for 1 book having 2 authors):
[{'title': u'book1', 'authors__name': u'author1'},{'title': u'book1', 'authors__name': u'author2'}]
我想要的是:
[{'title': u'book1', 'authors': [{'name':u'author1'},{'name':u'author2'}]}]
我可能在作者模型中有更多的字段,所以喜欢获得这些字段。
I may have more fields in the author model, so would like to get those fields as well.
我可以在单个查询中执行此操作吗?
Can I do this in a single query?
做某事像想要的结果?
推荐答案
Django 1.4
很好的问题,请使用 pr efetch_related :
In [3]: [{'name': b.name, 'authors': [a.name for a in b.authors.all()]} for b in Book.objects.prefetch_related('authors')]
(0.000) SELECT "test_app_book"."id", "test_app_book"."name" FROM "test_app_book"; args=()
(0.000) SELECT ("test_app_book_authors"."book_id") AS "_prefetch_related_val", "test_app_author"."id", "test_app_author"."name" FROM "test_app_author" INNER JOIN "test_app_book_authors" ON ("test_app_author"."id" = "test_app_book_authors"."author_id") WHERE "test_app_book_authors"."book_id" IN (1, 2); args=(1, 2)
Out[3]:
[{'authors': [u'a', u'b'], 'name': u'book'},
{'authors': [u'b'], 'name': u'test'}]
Django 1.3
prefetch_related在Django 1.4中引入。对于Django 1.3,您需要 django-selectreverse :
In [19]: [{'name': b.name, 'authors': [a.name for a in b.authors_prefetch]} for b in Book.objects.select_reverse({'authors_prefetch': 'authors'})]
(0.000) SELECT "test_app_book"."id", "test_app_book"."name" FROM "test_app_book"; args=()
(0.001) SELECT (test_app_book_authors.book_id) AS "main_id", "test_app_author"."id", "test_app_author"."name" FROM "test_app_author" INNER JOIN "test_app_book_authors" ON ("test_app_author"."id" = "test_app_book_authors"."author_id") WHERE "test_app_book_authors"."book_id" IN (1, 2); args=(1, 2)
Out[19]:
[{'authors': [u'a', u'b'], 'name': u'book'},
{'authors': [u'b'], 'name': u'test'}]
使用 django-selectreverse :
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, null=True, blank=True)
objects = ReverseManager()
这篇关于所有的价值观许多到很多领域:Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文