Limit choices to foreignkey in django rest framework

后端 未结 5 1086
半阙折子戏
半阙折子戏 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

    I would deal with this by overriding get_serializer_class to dynamically return a serializer class at runtime, setting the choices option on the field there:

    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
    

提交回复
热议问题