gpt4 book ai didi

python - 如何在 Django-Rest-Framework 中只深入一个领域?

转载 作者:行者123 更新时间:2023-12-04 13:21:32 27 4
gpt4 key购买 nike

我有一个 IPv4ListSerializer ,它有一个 depth = 1 :

class IPv4ListSerializer(ModelSerializer):
"""
ipv4
"""
ip_status = serializers.CharField(read_only=True)
class Meta:
model = IPv4Manage
fields = "__all__"
depth = 1

但结果却变成了每一个领域 depth 1 :
[
{
"id": 281,
"ip_status": "Vlaned",
"ip": "43.243.33.1",
"netmask": "255.255.255.248",
"prefix": 29,
"is_gateway": false,
"is_network_ip": false,
"is_broadcast_ip": false,
"desc": null,
"ctime": "2018-04-26T21:17:33.623092+08:00",
"uptime": "2018-06-02T12:48:41.882016+08:00",
"ipv4network": {
"id": 21,
"network_ip": "43.243.33.0",
"prefix": 24,
"ctime": "2018-04-26T21:17:33.533667+08:00",
"uptime": "2018-04-26T21:17:33.533814+08:00",
"area_partition": 7
},
"vlaned_ipv4network": {
"id": 1,
"network_ip": "43.243.33.0",
"prefix": 29,
"gateway_ip": "43.243.33.6",
"broadcast_ip": "43.243.33.7",
"ctime": "2018-04-26T21:27:56.011624+08:00",
"uptime": "2018-04-26T21:27:56.258053+08:00",
"ipv4network": 21,
"vlanedipv4networkgroup": 4
},
"physical_server": {
"id": 23,
"name": "SE01-A1",
"desc": "desc",
"cpu": "Intel Xeon E3-1230 v5",
"ram": "Supermicro DDR4___16",
"disk": "Inter SSD___240",
"price": "1000.00",
"server_status": "ready",
"pay_time": null,
"expire_time": null,
"ipmi_addr": "172.16.30.1",
"ipmi_account_and_pwd": null,
"has_intranet": true,
"intranet_ip": null,
"customer_desc": null,
"whmcs_tblorders_id": null,
"ctime": "2018-05-08T16:15:50.639962+08:00",
"uptime": "2018-08-20T18:25:27.289100+08:00",
"switches": 3,
"physical_server_model": 5,
"switchesport": 57,
"cabinet": 3,
"task": null,
"user": null,
"trade_record": null
}
},
....
]

我只能深入一个领域吗?比如如果 depth ipv4network ,我的要求是:
[
{
"id": 281,
"ip_status": "Vlaned",
"ip": "43.243.33.1",
"netmask": "255.255.255.248",
"prefix": 29,
"is_gateway": false,
"is_network_ip": false,
"is_broadcast_ip": false,
"desc": null,
"ctime": "2018-04-26T21:17:33.623092+08:00",
"uptime": "2018-06-02T12:48:41.882016+08:00",
"ipv4network": {
"id": 21,
"network_ip": "43.243.33.0",
"prefix": 24,
"ctime": "2018-04-26T21:17:33.533667+08:00",
"uptime": "2018-04-26T21:17:33.533814+08:00",
"area_partition": 7
},
"vlaned_ipv4network": 1,
"physical_server": 23,
},
....
]

最佳答案

depth 适用于 特定模型中的所有 FK 关系 .因此,如果您需要删除 深度特征 对于某些特定字段,对每个 fk 字段使用不同的序列化程序(类型 nested serializer)。

示例

class IPv4ListSerializer(ModelSerializer):
ip_status = serializers.CharField(read_only=True)
ipv4network = IPV4NetworkSerializer()

class Meta:
model = IPv4Manage
fields = "__all__"
depth = 1 # remove this "depth"

关于python - 如何在 Django-Rest-Framework 中只深入一个领域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52032122/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com