好的,我有两个类,一个是Book,另一个是Category。Book和Category由一个名为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获取书的数据时,我应该只获取类别名称,这一点我完全没有问题,但当我想查看类别的数据时,我想查看所有字段。但什么也没显示@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": [
{},
{}
]
}
型
还有一件事要注意的是,我只有2个类别内,我的数据库,这也是由它通过显示{},{}
2条答案
按热度按时间dgjrabp21#
您不需要嵌套序列化程序来获得您想要的结果。你可以像这样更改序列化器:
字符串
然后在视图中调用序列化程序时需要删除字段=('all')。
j7dteeu82#
在getCategory函数中,将serilized_data更改为
serilized_data = CategorySerializer(category,many=True)