多对多字段的所有值:Django

问题描述 投票:0回答:3

我有两个型号:

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 位作者的 1 本书):

[{'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 django-models django-queryset
3个回答
16
投票

Django 1.4

好问题,使用prefetch_lated

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_lated 是在 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()

4
投票

为了避免像 @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


0
投票

这个问题有一个解决方案。您可以将其与 ForeignKeyManyToManyField 一起使用。这是一个查询示例:

queryset = Student.objects.annotate(
        student_classes=ArrayAgg(
            JSONObject(id='classes__id', name='classes__name')
        ),
        student_user = JSONObject(name='user__name')
    ).values('id', 'student_user', 'student_classes')

在学生模型中,类是一个ManyToManyField,用户是一个ForeignKey。

输出

{'id': 6, 'student_classes': [{'id': 1, 'name': 'English Class'}, {'id': 1, 'name': 'Bangla'}], 'student_user': {'name': 'Sammrafi'}}
© www.soinside.com 2019 - 2024. All rights reserved.