我有以下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()
但这并不完全正确。我也认为序列化程序必须针对这种情况引发某种异常。如何执行呢?谢谢。
您可以为编写自定义权限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
也许只有一个数据库查询会更好:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句