自定义超链接URL字段,用于DRF

时间:2015-08-16 18:43:02

标签: python django serialization django-rest-framework drf-nested-routers

我正在使用Django Rest Framework为我的项目开发web api。在我的项目中,我需要构建嵌套的api的端点,如下所示:

   /users/ - to get all users
   /users/<user_pk> - to get details of a particular user
   /users/<user_pk>/mails/ - to get all mails sent by a user
   /users/<user_pk>/mails/<pk> - to get details of a mail sent by a user

所以,我正在使用drf-nested-routers来轻松写作&amp;维护这些嵌套资源。

我想要输出我的所有端点都有超链接,用于获取每个嵌套资源的详细信息以及其他详细信息:

[
    {
        "url" : "http://localhost:8000/users/1",
        "first_name" : "Name1",
        "last_name": "Lastname"
        "email" : "name1@xyz.com",
        "mails": [
            {
                 "url": "http://localhost:8000/users/1/mails/1",
                 "extra_data": "This is a extra data",
                 "mail":{
                     "url": "http://localhost:8000/mails/3"
                     "to" : "abc@xyz.com",
                     "from": "name1@xyz.com",
                     "subject": "This is a subject text",
                     "message": "This is a message text"
                 }
            },
            {
             ..........
            }
           ..........
         ]
    }
    .........
]

为此,我按照DRF文档继承HyperlinkedModelSerializer编写序列化程序,在序列化过程中自动添加url字段作为响应。

  

但是,默认情况下,DRF序列化程序不支持为上面提到的嵌套资源生成url,或者我们可以说不仅仅是单个查找字段。为了解决这种情况,他们建议create custom hyperlinked field

我遵循了这个文档,并编写了自定义代码来处理嵌套资源的url生成。我的代码片段如下:

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

# User model
class User(models.AbstractUser):
    mails = models.ManyToManyField('Mail', through='UserMail', 
                                     through_fields=('user', 'mail'))

# Mail model
class Mail(models.Model):
    to = models.EmailField()
    from = models.EmailField()
    subject = models.CharField()
    message = models.CharField()

# User Mail model
class UserMail(models.Model):
    user = models.ForeignKey('User')
    mail = models.ForeignKey('Mail')
    extra_data = models.CharField()

serializers.py

from rest_framework import serializers
from .models import User, Mail, UserMail
from .serializers_fields import UserMailHyperlink

# Mail Serializer
class MailSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Mail
        fields = ('url', 'to', 'from', 'subject', 'message' )

# User Mail Serializer
class UserMailSerializer(serializers.HyperlinkedModelSerializer):
    url = UserMailHyperlink()
    mail = MailSerializer()

    class Meta:
        model = UserMail
        fields = ('url', 'extra_data', 'mail')  


# User Serializer
class UserSerializer(serializers.HyperlinkedModelSerializer):
    mails = UserMailSerializer(source='usermail_set', many=True)

    class Meta:
        model = User
        fields = ('url', 'first_name', 'last_name', 'email', 'mails')

serializers_fields.py

from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import UserMail

class UserMailHyperlink(serializers.HyperlinkedRelatedField):
    view_name = 'user-mail-detail'
    queryset = UserMail.objects.all()

    def get_url(self, obj, view_name, request, format):
        url_kwargs = {
            'user_pk' : obj.user.pk,
            'pk' : obj.pk
        }
        return reverse(view_name, kwargs=url_kwargs, request=request, 
                          format=format)

    def get_object(self, view_name, view_args, view_kwargs):
        lookup_kwargs = {
           'user_pk': view_kwargs['user_pk'],
           'pk': view_kwargs['pk']
        }
        return self.get_queryset().get(**lookup_kwargs)

views.py

from rest_framework import viewsets
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .models import User, UserMail
from .serializers import UserSerializer, MailSerializer

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

class UserMailViewSet(viewsets.ViewSet):
    queryset = UserMail.objects.all()
    serializer_class = UserMailSerializer

    def list(self, request, user_pk=None):
        mails = self.queryset.filter(user=user_pk)
        serializer = self.serializer_class(mails, many=True,
            context={'request': request}
        )
        return Response(serializer.data)

    def retrieve(self, request, pk=None, user_pk=None):
        queryset = self.queryset.filter(pk=pk, user=user_pk)
        mail = get_object_or_404(queryset, pk=pk)
        serializer = self.serializer_class(mail,
            context={'request': request}
        )
        return Response(serializer.data)

urls.py

from rest_framework.routers import DefaultRouter
from rest_framework_nested import routers
from django.conf.urls import include, url
import views

router = DefaultRouter()
router.register(r'users', views.UserViewSet, base_name='user')

user_router = routers.NestedSimpleRouter(router, r'users',
    lookup='user'
)
user_router.register(r'mails', views.UserMailViewSet,
    base_name='user-mail'
)


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

现在,执行此操作后,当我运行项目并ping /users/ api端点时,我收到此错误:

  

AttributeError :&#39; UserMail&#39;对象没有属性&#39; url&#39;

我无法理解为什么会出现此错误,因为在UserMailSerializer我添加了url字段作为此序列化程序的属性,所以当它必须序列化为什么需要{{1}时} field作为url模型的属性。 请帮助我摆脱这个问题。

P.S:请不要在模型中建议任何重构。在这里,我只是用UserMail&amp; amp;伪装成我的项目真实想法。 user事。因此,将此作为测试用例并建议我一个解决方案。

1 个答案:

答案 0 :(得分:3)

我最近需要做类似的事情。我的解决方案最终制作了自定义关系字段。为了节省空间,我会简单地(并且无耻地)指向source code。最重要的部分是添加lookup_fieldslookup_url_kwargs类属性,这些属性在内部用于查找对象并构造URI:

class MultiplePKsHyperlinkedIdentityField(HyperlinkedIdentityField):
    lookup_fields = ['pk']
    def __init__(self, view_name=None, **kwargs):
        self.lookup_fields = kwargs.pop('lookup_fields', self.lookup_fields)
        self.lookup_url_kwargs = kwargs.pop('lookup_url_kwargs', self.lookup_fields)
        ...

反过来允许使用如下:

class MySerializer(serializers.ModelSerializer):
    url = MultiplePKsHyperlinkedIdentityField(
        view_name='api:my-resource-detail',
        lookup_fields=['form_id', 'pk'],
        lookup_url_kwargs=['form_pk', 'pk']
    )

以下是我如何使用它source code

希望这可以帮助你开始。