django-rest-framework:对嵌套数据进行GET和POST

时间:2014-08-10 13:02:43

标签: django django-rest-framework

this example为模型,每个用户都有多个相册,每张专辑都有很多曲目。

如何让我的用户获取并将曲目仅发布到他拥有的专辑? 我将使用哪个序列化程序以及如何设置我的视图?

这是我的模特:

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

class Album(models.Model):
    album_name = models.CharField(max_length=100)
    user = models.ForeignKey(User)

class Track(models.Model):
    album = models.ForeignKey(Album, related_name='tracks')
    order = models.IntegerField()
    title = models.CharField(max_length=100)
    duration = models.IntegerField()

    class Meta:
        unique_together = ('album', 'order')
        order_by = 'order'

    def __unicode__(self):
        return '%d: %s' % (self.order, self.title)

注意:我不是要求你为我完成所有工作。在线链接到特定示例就足够了,谢谢。

1 个答案:

答案 0 :(得分:0)

您所看到的是Object level permissions您需要添加自定义权限才能允许对象的所有者对其进行编辑。

这里有一个例子Object level permissions。另一个例子:

# models.py
class Message(BaseDate):
    """
    Private Message Model
    Handles private messages between users
    """
    status = models.SmallIntegerField(_('status'), choices=choicify(MESSAGE_STATUS))
    from_user = models.ForeignKey(User, verbose_name=_('from'), related_name='messages_sent')
    to_user = models.ForeignKey(User, verbose_name=_('to'), related_name='messages_received')
    text = models.TextField(_('text'))
    viewed_on = models.DateTimeField(_('viewed on'), blank=True, null=True)


# serialisers.py
class MessageSerializer(serializers.ModelSerializer):
    from_user = serializers.Field(source='from_user.username')
    to_user = serializers.Field(source='to_user.username')

    class Meta:
        model = Message
        fields = ('id', 'status', 'from_user', 'to_user', 'text', 'viewed_on')


# views.py
from permissions import IsOwner

class MessageDetail(generics.RetrieveUpdateDestroyAPIView):
    model = Message
    serializer_class = MessageSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (permissions.IsAuthenticated, IsOwner)


# permissions.py
class IsOwner(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit or delete it.
    """

    def has_permission(self, request, view, obj=None):
       # Write permissions are only allowed to the owner of the snippet
       return obj is None or obj.from_user == request.user


# urls.py
urlpatterns = patterns('',
    url(r'^messages/(?P<pk>[0-9]+)/$', MessageDetail.as_view(), name='api_message_detail'),
)