Limit choices to foreignkey in django rest framework

后端 未结 5 1165
半阙折子戏
半阙折子戏 2021-02-06 06:01

How to limit images of request.user to be linked with node. I wish I could do something like:

photo = models.ForeignKey(
    Image,
    limit_choices_to={\'owner         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 06:26

    You can create a custom foreign key field and define get_queryset() method there to filter related objects to only those of your user. The current user can be retrieved from the request in the context:

    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')
    

    This example is using Django REST Framework version 3.

提交回复
热议问题