Limit choices to foreignkey in django rest framework

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

    Because I am sure this logic will be used across an entire Django application why not make it more generic?

    class YourPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    
        def __init__(self, **kwargs):
            self.model = kwargs.pop('model')
            assert hasattr(self.model, 'owner')
            super().__init__(**kwargs)
    
    
        def get_queryset(self):
            return self.model.objects.filter(owner=self.context['request'].user)
    

    serializers.py

    class SomeModelSerializersWithABunchOfOwners(serializers.ModelSerializer):
    
        photo = YourPrimaryKeyRelatedField(model=Photo)
        categories = YourPrimaryKeyRelatedField(model=Category,
                                                many=True)
        # ...
    
    

提交回复
热议问题