从表面上看,这似乎是一个奇怪的请求,但我需要一个以逗号分隔的模型相关项目字符串。以任何教程中的作者/书籍模型为例,这就是我当前正在做的事情:
authors = Authors.objects.all().prefetch_related('books')
for author in authors:
author.book_titles = ', '.join([book.title for book in author.books.all()])
它一点也不重,但感觉多余。就像数据库可以做到这一点。在理想的世界中,我觉得我应该能够用这些奇特的新东西之一来注释这一点数据库功能。这是一个幻想的例子,使用一个名为的虚构函数Joiner(..)
:
Authors.objects.annotate(book_titles=Joiner('books__title', separator=', ')
那可能吗?如果是这样,怎么办?
from django.db.models import Aggregate, CharField, Value
class GroupConcat(Aggregate):
function = 'GROUP_CONCAT'
template = '%(function)s(%(expressions)s)'
def __init__(self, expression, delimiter, **extra):
output_field = extra.pop('output_field', CharField())
delimiter = Value(delimiter)
super(GroupConcat, self).__init__(
expression, delimiter, output_field=output_field, **extra)
def as_postgresql(self, compiler, connection):
self.function = 'STRING_AGG'
return super(GroupConcat, self).as_sql(compiler, connection)
Usage:
Author.objects.annotate(book_titles=GroupConcat('book__title', ', '))
定制聚合。这应该适用于 SQLite、MySQL 和 PostgreSQL。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)