如何更改 url 路由器 DRF 中的参数名称? [英] How i can change name of parameters in url routers DRF?
本文介绍了如何更改 url 路由器 DRF 中的参数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何更改 url 中某些参数的名称?像这样//,但参数的默认名称是pk"我向 "api/product/1/rate/1/"
发出请求并得到 {'product_pk': '1', 'pk': '1'}
.
How can I change the name of some parameters in url?
Like this //, but by default name of parameter is "pk"
I make request to "api/product/1/rate/1/"
and get {'product_pk': '1', 'pk': '1'}
.
我想将pk"重命名为person_id".
I want to rename "pk" to "person_id".
如何制作?
from rest_framework_nested import routers
router = routers.SimpleRouter()
router.register(r'product', ProductViewSet)
rate_router = routers.NestedSimpleRouter(router, r'product', lookup='product')
rate_router.register(r'rate', RateViewSet, base_name='rate')
推荐答案
您可以使用 lookup_field
和 lookup_url_kwarg
来控制它.以下是文档.
You can control this by using lookup_field
and lookup_url_kwarg
. Here are the docs.
- lookup_field - 应该用于执行单个模型实例的对象查找的模型字段.默认为'pk'.请注意,在使用超链接 API 时,您需要确保API 视图和序列化器类都设置了查找字段,如果您需要使用自定义值.
- lookup_url_kwarg - 用于对象查找的 URL 关键字参数.URL conf 应该包含一个关键字参数对应这个值.如果未设置,则默认使用与lookup_field 相同的值.
这篇关于如何更改 url 路由器 DRF 中的参数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文