在我serializers.py我可以這樣做:Django Rest Framework中的序列化器字段過濾?
class BoxSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.email')
playlist = PrimaryKeyRelatedField(allow_null=True, source='playlist.name',
queryset=Playlist.objects.all(), required=False)
class Meta:
model = Box
我甚至可以做這樣的事情(硬編碼,但工程):
playlist = PrimaryKeyRelatedField(allow_null=True, source='playlist.name',
queryset=Playlist.objects.filter(user=User.objects.get(id=4)), required=False)
我在這個新的,我想知道如果有一種方法,我可以通過一些方法或東西會做這樣的事情request.user:
(我知道這是不正確,這只是用來了解我的點):
playlist = PrimaryKeyRelatedField(allow_null=True, source='playlist.name',
queryset=Playlist.objects.filter(user=request.user), required=False)
或者,我可以做這樣的事情(同樣不正確的):
playlist = PrimaryKeyRelatedField(allow_null=True, source='playlist.name',
queryset='get_playlists', required=False)
def get_playlists(self):
user = self.context['request'].user
return Playlist.objects.filter(user=user)
Box的「用戶」是否應該與播放列表的「用戶」相同? – Mijamo