2014-03-04 86 views
6

如何限制request.user的圖像與節點鏈接。我希望我可以這樣做:在django rest框架中限制對外鍵的選擇

photo = models.ForeignKey(
    Image, 
    limit_choices_to={'owner': username}, 
) 

但request.user,而不是用戶名,我不希望使用本地線程。

models.py

class Node(models.Model): 
    owner = models.ForeignKey(User) 
    content = models.TextField() 
    photo = models.ForeignKey(Image) 

class Image(models.Model): 
    owner = models.ForeignKey(User) 
    file = models.ImageField(upload_to=get_upload_file_name) 

serializers.py

class ImageSerializer(serializers.ModelSerializer): 
    owner = serializers.Field('owner.username') 

    class Meta: 
     model = Image 
     fields = ('file', 'owner') 

class NodeSerializer(serializers.HyperlinkedModelSerializer): 

    class Meta: 
     model = Node 
     fields = ('content', 'photo', 'owner') 

回答

9

我會通過覆蓋get_serializer_class動態返回在運行時串行器類,設置在該領域中有選項choices處理這個:

def get_serializer_class(self, ...): 
    user = self.request.user 
    owner_choices = ... # However you want to restrict the choices 

    class ImageSerializer(serializers.ModelSerializer): 
     owner = serializers.Field('owner.username', choices=owner_choices) 

     class Meta: 
      model = Image 
      fields = ('file', 'owner') 

    return ImageSerializer 
+2

非常感謝您的回答對你驚人的工作。 – neelix

+1

這仍然是最好的方式嗎?似乎有點雜亂。寧願讓我的序列化器在全局範圍內進行測試 – Eldamir

+1

'serializers.Field'的構造函數似乎沒有'choices'參數了 –

2
class CustomForeignKey(serializers.PrimaryKeyRelatedField): 
    def get_queryset(self): 
     return Table.objects.filter(is_active=True) 

class Serializer(serializers.ModelSerializer): 
    (...) 
    table= CustomForeignKey() 
    class Meta: 
    (...) 

更容易爲:

class Serializer(serializers.ModelSerializer): 
    (...) 
    table = serializers.PrimaryKeyRelatedField(queryset=Table.objects.filter(is_active=True)) 
    class Meta: 
    (...) 
3

您可以創建一個自定義的外鍵字段,並定義get_queryset()方法有相關物件進行篩選,只有那些用戶的。目前用戶可以從上下文的請求被檢索:

class UserPhotoForeignKey(serializers.PrimaryKeyRelatedField): 
    def get_queryset(self): 
     return Image.objects.filter(owner=self.context['request'].user) 

class NodeSerializer(serializers.HyperlinkedModelSerializer): 
    photo = UserPhotoForeignKey() 
    class Meta: 
     model = Node 
     fields = ('content', 'photo', 'owner') 

這個例子是使用Django REST Framework版本3.