0

我的模型中有一个ManyToMany字段。在序列化程序中,我能够获取嵌套的序列化数据,但我想对其进行规范化。

模型.py

class Authors(models.Model):
   name = models.CharField(max_length=20)
    
   class Mets:
      db_table = "authors"

class Books(models.Model):
   book_name = models.CharField(max_length=100)
   authors = models.ManyToManyField(Authors, related_names="books")

   class Meta:
      db_table = "books"

序列化程序.py

class AuthorSerializer(serializer.ModelSerializer):
   name = serializer.CharField()
   
   class Meta:
      model = Authors
      field = ("name",)

class BooksSerializer(serializer.ModelSerializer):
   authors = AuthorSerializer()
   
   class Meta:
      model = Books
      field = ("book_name", "authors")

上面的输出将是:

"result": [
 {
   "book_name": "Sample",
   "authors": [
    {
      "name": "Person 1",
    },
    {
      "name": "Person 2",
    }
   ]
  }
]

但我想输出这样的东西:

"result": [
 {
   "book_name": "Sample",
   "author_name": "Person 1",
 },
 {
   "book_name": "Sample",
   "author_name": "Person 2",
 },
]

更新

视图.py

class ReportViewSet(XLSXFileMixin, viewsets.ReadOnlyModelViewSet):
    serializer_class = BookSerializer
    renderer_classes = [XLSXRenderer]
    filename = 'my_export.xlsx'

    def get_queryset(self):
            queryset = Book.objects.all()
            book_id = self.request.query_params.get("pk", None)
            if book_id is not None:
                queryset = queryset.filter(id=book_id)
            return queryset

excel 报告应该有列:book_name,author_name

但是通过@Klim Bim 给出的解决方案,我得到了一个空的excel 报告,其中只有列名:book_nameauthors.

提前致谢。

4

1 回答 1

0

如果你想改变显示的行为,你必须重写to_representation()

def to_representation(self, instance):
   data = super().to_representation(instance)
   authors = data.pop('authors')
   retval = list()
   for author in authors:
     retval.append({**data, "author_name": author.get("name")})

   return {"result": retval}
于 2021-10-12T06:31:11.003 回答