好,我有两个类,一个是Book,另一个是Category.Book和Category由一个名为Category的外键链接,该外键是一个Book字段. 请参阅代码

class Category(models.Model):
    class Meta:
        verbose_name_plural = "Categories"

    category = models.CharField(max_length=20)

    def __str__(self):
        return self.category


class Book(models.Model):
    book_title = models.CharField(max_length=20)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def __str__(self):
        return self.book_title

下面是序列化程序类


class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)

        # Instantiate the superclass normally
        super().__init__(*args, **kwargs)

        if fields is not None:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)


class CategorySerializer(DynamicFieldsModelSerializer):
    class Meta:
        model = Category
        # only show the category field 
        fields = ['category']

class BookSerializer(serializers.ModelSerializer):
    # this will show the category data which is related to this Book
    category = CategorySerializer()
    class Meta: 
        model = Book
        fields = '__all__'

现在我希望,当我使用@api_view获取图书的数据时,我应该只获得类别名称,这是完全没有问题的,但当我想要查看Category的数据时,我希望看到所有字段.但它什么也没显示出来. @api_view代码

@api_view(['GET'])
def getBooks(request):
    books = Book.objects.all()
    serilized_data = BookSerializer(books,many=True)
    return Response({'status': 200, 'payload': serilized_data.data})


# it is now only show the category as only category field is passed in CategorySerilizer
@api_view(['GET'])
def getCategory(request):
    category = Category.objects.all()
    serilized_data = CategorySerializer(category,fields = ('__all__'),many=True)
    return Response({'status': 200, 'payload': serilized_data.data})

而getCategory的输出是


{
    "status": 200,
    "payload": [
        {},
        {}
    ]
}

还有一件事需要注意的是,我的数据库中只有两个类别,它也通过{},{}显示

推荐答案

您不需要嵌套序列化程序来获得您想要的结果.您可以这样更改序列化程序:

    class CategorySerializer(DynamicFieldsModelSerializer):
        class Meta:
            model = Category 
            fields = '__all__'
    
    class BookSerializer(serializers.ModelSerializer):
        # Now your only getting the name of the category without having to nest the serializers
        category = serializers.ReadOnlyField(source="category.category")
    
        class Meta: 
            model = Book
            fields = '__all__'

然后,在调用视图中的序列化程序时,需要删除字段=(‘__all’__).

Python相关问答推荐

tempfile.mkstemp(text=.)参数实际上是什么?

为什么Pydantic在我申报邮箱时说邮箱丢失

日程优化问题不知道更好的方式来呈现解决方案- Python / Gekko

流畅的模式,采用Escc方法

两极:滚动组,起始指数由不同列设置

Pandas 按照特殊规则保留每n行

Pandas 群内滚动总和

单击Python中的复选框后抓取数据

无法导入已安装的模块

使文本输入中的文本与标签中的文本相同

如何在BeautifulSoup中链接Find()方法并处理无?

替换字符串中的多个重叠子字符串

Vectorize多个头寸的止盈/止盈回溯测试pythonpandas

发生异常:TclMessage命令名称无效.!listbox"

将9个3x3矩阵按特定顺序排列成9x9矩阵

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

我如何根据前一个连续数字改变一串数字?

SQLAlchemy bindparam在mssql上失败(但在mysql上工作)

如何合并两个列表,并获得每个索引值最高的列表名称?

如何在PySide/Qt QColumbnView中删除列