Django Rest框架使用网址中的点 [英] Django Rest Framework using dot in url

查看:292
本文介绍了Django Rest框架使用网址中的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用DRF(Django Rest框架)我的一个模型有一个IP地址作为主键。

Using DRF (Django Rest Framework) one of my models has an IP Address as primary key.

class VTE(models.Model):
  ipaddr = models.CharField(primary_key=True, max_length=16)
  ...

问题是PK包含点,当REST URL被组装时,点被解释为DRF的格式化选项,而不是主键的一部分。请参阅以下错误和匹配模式。

The problem is that the PK contains dots, and when the REST URL is assembled the dots are interpreted as formatting options by DRF instead as part of the primary key. See the error below, and the matching patterns.

Request URL:    http://192.168.10.121/api/vtes/172.25.128.29/

Using the URLconf defined in vtfx.urls, Django tried these URL patterns, in this order:

...
^api/ ^$ [name='api-root']
^api/ ^\.(?P<format>[a-z0-9]+)$ [name='api-root']
^api/ ^vtes/$ [name='vte-list']
^api/ ^vtes/\.(?P<format>[a-z0-9]+)$ [name='vte-list']   <---- HERE
^api/ ^vtes/(?P<pk>[^/.]+)/$ [name='vte-detail']
^api/ ^vtes/(?P<pk>[^/.]+)/\.(?P<format>[a-z0-9]+)$ [name='vte-detail']
...

使用点作为主键的一部分是错误的如果不是与DRF路由器汇编这些URL是不一致的。

it's wrong to use dots as part of the primary key? If not it's kind of incompatible with how the DRF router assembly the URLs.

是否有DRF解决方法?

更新:上下文

api.py:
 class VTESerializer(serializers.ModelSerializer):
     class Meta:
         model = models.VTE

 class VTEViewSet(viewsets.ModelViewSet):
     queryset = models.VTE.objects.all()
     serializer_class = VTESerializer
     permission_classes = (permissions.AllowAny,)

urls.py:
 router = routers.DefaultRouter()
 router.register(r'vtes', api.VTEViewSet) 

 urlpatterns = patterns('',
     url(r'^api/', include(router.urls)),
     ...
 )


推荐答案

首先,可以使用(点)在urls。见
可以。 (期间)是URL的路径部分的一部分?

First, it's ok to use the . (dot) in urls. See Can . (period) be part of the path part of an URL?

其次,问题不在格式选项,但在用于捕获主键的正则表达式表达式中排除(点)和 / (slash)每个默认值。

Second, the problem wasn't in the format option but in the Regex expression used to catch the Primary Key, which excludes the . (dot) and / (slash) per default.

(?P<pk>[^/.]+)  <--- This excludes the dots in the IP Address

正则表达式可以在ViewSet中被覆盖, lookup_value_regex 。这是解决问题的新ViewSet:

The regex can be overrided in the ViewSet with lookup_value_regex. This is the new ViewSet that solves the problem:

class VTEViewSet(viewsets.ModelViewSet):
    lookup_value_regex = '[0-9.]+'      #Just add this line & change your Regex if needed
    queryset = models.VTE.objects.all()
    serializer_class = VTESerializer
    permission_classes = (permissions.AllowAny,)

这篇关于Django Rest框架使用网址中的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆