Python 我的路由中需要什么 base_name 参数才能使这个 Django API 工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22083090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:12:12  来源:igfitidea点击:

What base_name parameter do I need in my route to make this Django API work?

pythondjangorest

提问by Saqib Ali

I am building a Django application that exposes a REST API by which users can query my application's models. I'm following the instructions here.

我正在构建一个 Django 应用程序,它公开了一个 REST API,用户可以通过它查询我的应用程序的模型。我正在按照此处的说明进行操作。

My Route looks like this in myApp's url.py:

我的路由在 myApp 的 url.py 中是这样的:

from rest_framework import routers
router = routers.DefaultRouter()    router.register(r'myObjects/(?P<id>\d+)/?$', views.MyObjectsViewSet)
url(r'^api/', include(router.urls)),

My Model looks like this:

我的模型看起来像这样:

class MyObject(models.Model):
    name = models.TextField()

My Serializer looks like this:

我的序列化程序如下所示:

class MyObjectSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MyObject
    fields = ('id', 'name',)

My Viewset looks like this:

我的视图集如下所示:

class MyObjectsViewSet(viewsets.ViewSet):

    def retrieve(self,request,pk=None):
        queryset = MyObjects.objects.get(pk=pk).customMyObjectList()

        if not queryset:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            serializer = MyObjectSerializer(queryset)
            return Response(serializer.data,status=status.HTTP_200_OK)

When I hit /api/myObjects/60/ I get the following error:

当我点击 /api/myObjects/60/ 时,出现以下错误:

base_nameargument not specified, and could not automatically determine the name from the viewset, as it does not have a .modelor .querysetattribute.

base_name未指定参数,并且无法从视图集中自动确定名称,因为它没有.modelor.queryset属性。

I understand from herethat I need a base_name parameter on my route. But from the docs, it is unclear to me what that value of that base_name parameter should be. Can someone please tell me what the route should look like with the base_name?

我从这里了解到我的路线上需要一个 base_name 参数。但是从文档中,我不清楚那个 base_name 参数的值应该是什么。有人可以告诉我 base_name 的路线应该是什么样的吗?

回答by GreenGuerilla

An alternative solution might be to use a ModelViewSetwhich will derive the basename automatically from the model.

另一种解决方案可能是使用ModelViewSet,它会自动从模型中派生出基本名称。

Just make sure and tell it which model to use:

只需确保并告诉它使用哪个模型:

Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes, or the model attribute shortcut.

因为 ModelViewSet 扩展了 GenericAPIView,您通常需要至少提供 queryset 和 serializer_class 属性,或模型属性快捷方式。

回答by Eric Lee

Try doing this in your urls.py. The third parameter 'Person' can be anything you want.

尝试在您的 urls.py 中执行此操作。第三个参数“人”可以是任何你想要的。

router.register(r'person/food', views.PersonViewSet, 'Person')

回答by Hugo Hernani

Maybe you just need to set the base_nameparameter for your router with the name of the object: MyObject, in your case.

也许您只需要base_name使用对象名称为您的路由器设置参数:MyObject,在您的情况下。

router.register(r'myObjects/(?P<id>\d+)/?$', views.MyObjectsViewSet, base_name="MyObject")

http://www.django-rest-framework.org/api-guide/routers/#Usage

http://www.django-rest-framework.org/api-guide/routers/#Usage

回答by Mohideen bin Mohammed

simply mention this,

简单提一下,

queryset = MyObjects.objects.all()

like this,

像这样,

class MyObjectsViewSet(viewsets.ViewSet):
    queryset = MyObjects.objects.all()

in your corresponding Viewset in views.py instead of mentioning under

在 views.py 中相应的 Viewset 中,而不是在下面提及

def retrieve()...

定义检索()...

its worked for me :)

它对我有用:)

回答by ingaham

thisis a useful answer, read for the details.

是一个有用的答案,请阅读详细信息。

tl;dr

tl;博士

It is used as the base name of the generated URL patterns (e.g., 'myobject-detail' or 'myobject-list').

它用作生成的 URL 模式的基本名称(例如,“myobject-detail”或“myobject-list”)。

回答by Sriram

Let me explain, why we need an base_namein the first place and then let's go into the possible value of base_name.

让我解释一下,为什么我们首先需要一个base_name,然后让我们进入base_name的可能值。

If you ever used the Django urls withoutthe rest-framework (DRF) before, you would've specified it like this:

如果你以前使用过没有rest-framework (DRF)的 Django url ,你会像这样指定它:

urlpatterns = [
    url(r'myObjects/(?P<id>\d+)/?$', views.MyObjectsListView.as_view(), name='myobject-list'),
    url(r'myObjects/(?P<id>\d+)/?$', views.MyObjectsDetailView.as_view(), name='myobject-detail'),
]

Here, if you see, there is a nameparameter which used to identify the url in the currentnamespace (which is app).

在这里,如果您看到,有一个name参数用于标识当前命名空间(即 app)中的 url 。

This is exactly what django-rest-framework trying to do automatically, since the drfknows whether the view is listor detail(because of viewset). it just needs to append some prefixto differentiate the urls. That's the purpose of base_name(prefix).

这正是 django-rest-framework 尝试自动执行的操作,因为drf知道视图是列表还是细节(因为视图集)。它只需要附加一些前缀来区分网址。这就是base_name(前缀)的目的。

In most scenario, you can give the urlor resource nameas base_name. In your case, base_name=myobject. DRF will generate base_name + view_typeas the nameparameter like myobject_list& myobject_detail.

在大多数情况下,您可以将url资源名称指定base_name。在您的情况下,base_name=myobject。DRF 将生成base_name + view_type作为名称参数,如myobject_list& myobject_detail

Note: Usually, base_namewill be automaticallyobtained from the querysetfield (from view), since it's same for all view types in a viewset. But if you specify, get_querysetmethod instead of queryset, it possibly means you've different queryset for different view types (like list, detail). So, DRF will ask you to specify a common base_namefor all the view types for a resource.

:通常情况下,BASE_NAME自动从所获得的查询集字段(从视图),因为它是同为在视图集中的所有视图类型。但是,如果您指定get_queryset方法而不是queryset,则可能意味着您对不同的视图类型(如列表、详细信息)有不同的查询集。因此,DRF 会要求您为资源的所有视图类型指定一个公共base_name