有没有一种方法可以将列表值作为自定义聚合列注入queryset

时间:2019-04-21 16:04:32

标签: python django django-queryset

我正在寻找一种从诸如Author之类的具有字段[pk,名称]和Book [pk,作者,标题,已发布]的模型中查询数据的方法,因此,最后,我会有类似的东西

[
  {
    'pk': 'author_pk_1', 'name': 'author__name_1', 'books': [
      {
        'pk': 'book__pk_1',
        'title': 'book_name_1',
        'published': 'book_published_1',
      },
      {
        'pk': 'book__pk_2',
        'title': 'book_name_2',
        'published': 'book_published_2',
      }
    ]
  }
]

目前,我通过遍历QuerySet并将其手动分组来实现此目的,但是看起来一点也不好:

authors = Author.objects.values('pk', 'name')
grouped = list()
for author in authors:
    entry = dict()
    entry['pk'] = author['pk']
    entry['name'] = author['name']
    entry['books'] = list(Book.objects.filter(author=author['pk']).values('pk', 'title', 'published'))
    grouped.append(entry)

更新:

嗯,这比我想象的要容易。这是我到目前为止所拥有的:

view.py

@api_view(['GET'])
def api_get_grouped_books(request, *args, **kwargs):
  if request.method == 'GET':
    authors = Author.objects.all()
    serializer = AuthorSerializer(authors, many=True)
    return Response(serializer.data)

serializers.py

class BookSerializer(serializers.ModelSerializer):
  class Meta:
    model = Book
    fields = ('title', 'published', )


class AuthorSerializer(serializers.ModelSerializer):

  books = BookSerializer(many=True)

  class Meta:
    model = Author
    fields = ('name', 'books', )

  def create(self, validated_data):
    books_data = validated_data.pop('books')

    author, _ = Author.objects.get_or_create(
      name=validated_data.get('name'),
      defaults=validated_data
    )

    for book_data in books_data:
      try:
        Book.objects.get(title=book_data.get('title'))
      except ObjectDoesNotExist:
        Book.objects.create(author=author, **book_data)

    return author

注意:起初,当我尝试发布一些数据时遇到了AttributeError-它抱怨字段books不是Author模型的一部分,所以我最终添加了属性{ related_name='books'模型中的{1}}到author ForeignKey字段。

0 个答案:

没有答案