python - Django REST Framework 深度仅适用于指定字段
问题描述
所以我有一个Django REST 框架序列化器。现在我为我的博客文章添加了一个序列化程序,但我只希望指定字段的序列化程序深度。直到现在我得到这个:
{
"results": [
{
"postid": 1,
"title": "Test Title",
"slug": "test-title",
"description": "Test Description",
"tag": {
"tagid": 1,
"tagname": "school"
},
"views": 15,
"release_date": "2021-05-25T17:15:22.223311Z",
"user": {
"userid": 1,
"password": "pbkdf2_sha256$216000$drVQlm6CdO+g90ygM3gXFUHBb+ctaKDA=",
"username": "user1",
"email": "testemail@gmail.com",
"posts": 0,
"date_joined": "2021-05-25T17:13:29.865119Z",
"last_login": "2021-05-25T17:14:12.808671Z",
"is_admin": true,
"is_active": true,
"is_staff": true,
"is_superuser": true
},
"city": "New York",
"country": {
"countryid": 1,
"continent": "america",
"countryname": "usa",
"currency": "$",
"symbol": "US"
}
},
...
]
}
这是我的序列化器:
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = Job
fields = ["postid", "title", "description", "slug", "tag", "views", "user", "release_date", "city", "country"]
depth = 1
但问题是,我只想要标签和国家的深度,而不是用户:/ 像这样:
{
"results": [
{
"postid": 1,
"title": "Test Title",
"slug": "test-title",
"description": "Test Description",
"tag": {
"tagid": 1,
"tagname": "school"
},
"views": 15,
"release_date": "2021-05-25T17:15:22.223311Z",
"user": 1,
"city": "New York",
"country": {
"countryid": 1,
"continent": "america",
"countryname": "usa",
"currency": "$",
"symbol": "US"
}
},
...
]
}
你有过同样的问题吗?谢谢你的帮忙 :)
解决方案
假设您还有标签和国家/地区的序列化程序:
class BlogPostSerializer(serializers.ModelSerializer):
tag = TagSerializer(read_only=True)
country = CountrySerializer(read_only=True)
class Meta:
model = Job
fields = ["postid", "title", "description", "slug", "tag", "views", "user", "release_date", "city", "country"]
推荐阅读
- snipcart - Snipcart v3 和“data-item-stackable”属性
- html - JQuery 无法连续更改 2 个数据属性
- c++ - 为什么我们不能直接将二维数组的地址分配给指针?
- mongodb - 将数组元素与另一个数组合并,该数组是 mongo 集合的一部分
- fluent-assertions - 如何使用 FluentAssertions 中的 BeEquivalentTo 比较两个简单的字典?
- mysql - 在 presto 中使用正则表达式仅在最后一个斜杠前面有一个字符时才删除它
- java - Java密码游戏
- cmake - 编译自己的项目时 gtkmm 4.0 标头构建错误
- linux - 无法在 laravel 公用文件夹中写入
- c - 为什么C中的这两个刺不相等?