gpt4 book ai didi

django - 多对多字段的所有值:Django

转载 作者:行者123 更新时间:2023-12-03 23:43:07 24 4
gpt4 key购买 nike

我有两个模型:

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)


现在,我想要所有书籍的信息。所以我做了:

book_info = Book.objects.all().values('title', 'authors__name')


并且,它给出的输出类似于(对于一本有2位作者的书):

[{'title': u'book1', 'authors__name': u'author1'},{'title': u'book1', 'authors__name': u'author2'}]


我想要的是这样的:

[{'title': u'book1', 'authors': [{'name':u'author1'},{'name':u'author2'}]}]


我可能在作者模型中有更多字段,所以也想获得这些字段。

我可以在一个查询中执行此操作吗?

我该怎么做才能得到想要的结果?

最佳答案

Django 1.4

很好的问题,请使用prefetch_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 - 多对多字段的所有值:Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12139923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com