Django REST:url-reverse中的奇怪点

时间:2016-12-21 15:24:53

标签: python django django-rest-framework

router代码:

...
domain_nested_routers_lookup = 'domain'
router = routers.DefaultRouter()
router.register('accounts', DomainViewSet)
...
domains_router = NestedSimpleRouter(router, r'accounts', lookup=domain_nested_routers_lookup)

此举的原因是项目旧API使用的术语domain未更改为account

serializer代码:

class DomainSerializer(...):
    link = serializers.HyperlinkedIdentityField(view_name='domain-detail', lookup_field='short_name')

现在的问题是这段代码:

self.api_reverse('domain-detail', self.domain.id)

返回:

u'/rest/accounts/domain_0.1'

我不理解添加了什么魔法.1(1是id domainu'/rest/accounts/domain_0对象。

正确的输出应该是:

.. toctree:: :hidden: filename

2 个答案:

答案 0 :(得分:2)

因此,如果您的URL路由中定义了参数,则可以传入一组参数进行反转。我之前没有使用过django REST,但我会尝试命名你的参数:

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.require_version ">= 1.4.3"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  if ENV["KONG_PATH"]
    source = ENV["KONG_PATH"]
  else
    source = "./"
  end

  if ENV['KONG_VB_MEM']
    memory = ENV["KONG_VB_MEM"]
  else
    memory = 2048
  end

  if ENV["KONG_VERSION"]
    version = ENV["KONG_VERSION"]
  else
    version = "0.7.0"
  end

  config.vm.provider :virtualbox do |vb|
   vb.name = "vagrant_kongDEBUG"
   vb.memory = memory
  end
config.vm.box = "centos/7"
      config.vm.synced_folder ".", "/tmp", type: "rsync"

  config.vm.network :forwarded_port, guest: 8000, host: 8000
  config.vm.network :forwarded_port, guest: 8001, host: 8001
  config.vm.network :forwarded_port, guest: 8443, host: 8443

  config.vm.provision "shell", inline: "cd /tmp"
  config.vm.provision "shell", inline: "ls -l"
  config.vm.provision "shell", path: "provision.sh", :args => version
end

或 -

self.api_reverse('domain-detail', args=[ self.domain.id ])

这可能会产生如下路线:

self.api_reverse('domain-detail', kwargs={'pk': self.domain.id })

答案 1 :(得分:0)

在寻找答案并从 2ps 获得帮助后,我已经找到了方法:

self.api_reverse('domain-detail'

就我而言,我必须更好地了解api_reverse的定义。