我没有在Django网站上看到我的对象

时间:2017-07-17 17:21:47

标签: python django python-3.x django-models django-rest-framework

我尝试创建Django内置API文档但是我无法将对象添加到左侧的列表中。当我打开localhost:8000/docs/时,我看不到the official Django REST documentation顶部的对象列表(在本例中为片段和用户)。目前我正在尝试这种方式:

urls.py:

from rest_framework.documentation import include_docs_urls

API_TITLE = 'API title'
API_DESCRIPTION = '..df.'

urlpatterns = [
 url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)),
]

models.py:

class Object1(models.Model):

    user = models.ForeignKey(User)
    value = models.FloatField()

admin.py基于developer.mozilla.org

from django.contrib import admin
from .models import Object1
# Register your models here.


admin.site.register(Object1)

我也基于https://docs.djangoproject.com,我尝试使用此admin.py版本:

class Object1Admin(admin.ModelAdmin):
    pass
admin.site.register(Object1, Object1Admin)

我也在使用其他版本,但我也没有得到积极的结果。有什么建议吗?

更新 我试图在我的视图文件中创建ViewSet并将其导入url以定义路由器为Raja Simon建议:

views.py:

from rest_framework import viewset


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()

urls.py:

from rest_framework.routers import DefaultRouter

# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'users', views.UserViewSet)

urlpatterns = [
    url(r'^', include(router.urls))
]

然而,我没有达到我想要的目标。此时我在Django网站上的列表以这种方式显示: enter image description here

但我希望在这种情况下拥有我的对象列表: enter image description here

2 个答案:

答案 0 :(得分:0)

更改此

user = models.ForeignKey(User)

user = models.ForeignKey('auth.User')

应该可行。

答案 1 :(得分:0)

只需在视图文件中创建ViewSet并将其导入url以定义路由器

<强> views.py

# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'users', views.UserViewSet)

url(r'^', include(router.urls)),

<强> urls.py

In [35]: df['541513_answer'] = df.string_col.str.extract(r'541513(\w+)', expand=True)

In [36]: df
Out[36]:
                                          string_col 541513_answer
0                            541511N~541512N~541513N             N
1                                    332710Y~332999Y           NaN
2                                               Null           NaN
3  238210Y~423690Y~517911Y~517919Y~532490Y~561421...           NaN