Django REST:如何在应用程序级别urls.py中使用Router?

时间:2015-01-01 07:16:46

标签: python django django-rest-framework

我的Django项目结构:

mysite/
    mysite/
        ...
        urls.py
    scradeweb/
        ...
        models.py
        serializers.py
        views.py
        urls.py
    manage.py

如果我在项目级别urls.py(router)中使用Django REST mysite/urls.py,如下所示,一切正常:

# mysite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from .settings import USER_CREATED_APPS
from rest_framework.routers import DefaultRouter
from scradeweb import views

router = DefaultRouter()
router.register(r'threads', views.ThreadViewSet, )
router.register(r'posts', views.PostViewSet)

urlpatterns = patterns('',
                url(r'^admin/', include(admin.site.urls)),
                url(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')),
                url(r'scradeweb/', include('scradeweb.urls', namespace='scradeweb')),
                url(r'^', include(router.urls)),
                )

我喜欢将我的所有应用程序(scradeweb)相关代码保存在其中 目录,所以我将router移到scradeweb/urls.py

# scradeweb/urls.py
from django.conf.urls import url, patterns, include
from scradeweb import views
from rest_framework.routers import DefaultRouter


router = DefaultRouter()
router.register(r'threads', views.ThreadViewSet, )
router.register(r'posts', views.PostViewSet)

urlpatterns = router.urls

当我转到http://127.0.0.1:8000/scradeweb/posts/时,它会引发异常:

ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "thread-detail". 
You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.

为什么不起作用?

这是我的scradeweb/models.py

class Thread(models.Model):

    thread_id = models.IntegerField()
    sticky = models.NullBooleanField()
    prefix = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    start_time = models.DateTimeField()
    author = models.CharField(max_length=255)
    url = models.URLField(unique=True)
    forum = models.ForeignKey(Forum, related_name='threads')

    class Meta:
        ordering = ('start_time', )


class Post(models.Model):

    post_id = models.IntegerField()
    url = models.URLField(unique=True)
    post_number = models.IntegerField()
    start_time = models.DateTimeField(blank=True)
    last_edited_time = models.DateTimeField(blank=True, null=True)
    author = models.CharField(max_length=255, blank=True)
    content = models.TextField(blank=True)
    thread = models.ForeignKey(Thread, related_name='posts')

    class Meta:
        ordering = ('post_number', )

scradeweb/serializers.py

from rest_framework import serializers
from scradeweb.models import Thread, Post


class ThreadSerializer(serializers.HyperlinkedModelSerializer):

    posts = \
        serializers.HyperlinkedRelatedField(
            many=True,
            read_only=True,
            view_name='post-detail',
        )

    class Meta:

        model = Thread
        fields = ('pk', 'thread_id', 'title', 'url', 'posts')
        read_only_fields = ('thread_id', )


class PostSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Post

scradeweb/views.py

...

class ThreadViewSet(viewsets.ReadOnlyModelViewSet):

    queryset = Thread.objects.all()
    serializer_class = ThreadSerializer


class PostViewSet(viewsets.ModelViewSet):

    queryset = Post.objects.all()
    serializer_class = PostSerializer

1 个答案:

答案 0 :(得分:18)

这里的问题是您正在使用带有命名空间的Django REST Framework。许多组件与它们不兼容,并不意味着它们无法使用,因此您需要通过执行大量手动工作来解决这些问题。主要问题是超链接关系(Hyperlinked*Field s),因为它们必须反转视图,并且需要指定命名空间。

首先是路由器级别,目前不支持命名空间。这只是DefaultRouter的问题,因为它将构建包含反转网址列表的索引页面,这将立即触发错误。 这已经修复in the upcoming release ,但是现在你已经没有它了。最好(DRF 3.0+),索引页面将完全为空(或指向不正确的URL),在最坏的情况下(DRF 2.x),它将始终触发内部服务器错误。

第二个要看的是序列化器字段。默认情况下,HyperlinkedModelSerializer会自动生成包含非命名空间网址的HyperlinkedRelatedFieldHyperlinkedIdentityField字段。当您使用名称空间时,必须覆盖所有这些自动生成的字段。这通常意味着您最好不要使用HyperlinkedModelSerializer,而是使用ModelSerializer来控制输出。

要修复的第一个(也是最简单的)是为所有对象自动生成的url字段。这是自动生成的,view_name设置为详细信息页面(在本例中为thread-detail),没有命名空间。您将需要覆盖view_name并在其前面包含命名空间(在这种情况下为scradeweb:thread-detail)。

class ThreadSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(
        view_name="scradeweb:thread-detail",
    )

您还需要覆盖所有自动生成的相关字段。对于可写字段,这稍微有些困难,但我总是建议在这些情况下查看repr(MySerializer())以查看自动生成字段的参数。对于只读字段的情况,只需复制默认参数并再次更改view_name即可。

class ThreadSerializer(serializers.ModelSerializer):
    posts = serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='scradeweb:post-detail',
    )

这将需要为所有字段完成,并且它看起来不像Django REST Framework将添加在不久的将来自动执行它的能力。虽然这一开始并不令人愉快,但它会给你一个很好的机会来欣赏DRF之前为你做的一切。