Django-REST外键对象权限

时间:2016-03-10 16:45:32

标签: django django-rest-framework

我有以下django模型:

class Photo(models.Model):
    album = models.ForeignKey('Album', related_name='photos')
    owner = models.ForeignKey('auth.User')

class Album(models.Model):
    title = models.CharField(max_length=100)
    owner = models.ForeignKey('auth.User')

IsOwner权限

class IsOwner(permissions.BasePermission):
    """
    Custom permission to only allow owners to get it.
    """

    def has_object_permission(self, request, view, obj):

        return obj.owner == request.user

我需要阻止使用其他用户拥有的照片创建相册。目前我使用这个解决方案:

class AlbumSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        photos = validated_data.pop('photos')

        for _photo in photos:
            ph_obj = Photo.objects.get(id=_photo['id'])
            if self.context['request'].user == ph_obj.owner:
                ph_obj.album = album
                ph_obj.save()

但它感觉不太对劲。另外我认为序列化器必须为这种情况引发某种异常。 怎么做? 感谢。

1 个答案:

答案 0 :(得分:2)

您可以为AlbumSerializer编写自定义权限以进行检查:

class CustomerAccessPermission(permissions.BasePermission):
    message = 'You can only add your photos!'

    def has_permission(self, request, view):

        if view.action == 'create':
            for photo in request.POST.get('photos'):
                if not Photo.objects.filter(id=photo['id'], owner=request.user).exists():
                    return False
        return True

或者只有一个db查询可能更好:

class CustomerAccessPermission(permissions.BasePermission):
    message = 'You can only add your photos!'

    def has_permission(self, request, view):

        if view.action == 'create':
            user_photos = Photo.objects.filter(owner=request.user).values_list('id', flat=True)
            for photo in request.POST.get('photos'):
                if not photo['id'] in user_photos:
                    return False
        return True