多对多字段的所有值:Django

时间:2012-08-27 10:05:15

标签: django django-models django-queryset

我有两种模式:

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')

并且,它给出了一个输出(对于1本书有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'}]}]

我可能在作者模型中有更多字段,因此也希望获得这些字段。

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

我能做些什么来获得所需的结果?

2 个答案:

答案 0 :(得分:12)

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()

答案 1 :(得分:1)

为了避免在@jpic的描述性答案中进行两次查询,您可以随后手动合并您的结果。对我来说感觉有些笨拙,但它确实有效。

def merge_values(values):
    grouped_results = itertools.groupby(values, key=lambda value: value['id'])
    merged_values = []
    for k, g in grouped_results:
        groups = list(g)
        merged_value = {}
        for group in groups:
            for key, val in group.iteritems():
                if not merged_value.get(key):
                    merged_value[key] = val
                elif val != merged_value[key]:
                    if isinstance(merged_value[key], list):
                        if val not in merged_value[key]:
                            merged_value[key].append(val)
                    else:
                        old_val = merged_value[key]
                        merged_value[key] = [old_val, val]
        merged_values.append(merged_value)
    return merged_values

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

merge_values函数取自this gist