シリアライザーのフィールド読み取り/書き込みの主な問題は、簡単に悪用できることです。 たとえば、「name」というフィールドにユーザー データを格納するモデルがある場合、データベースからユーザーの名前を読み取り、それをモデルの「name」フィールドに書き込むシリアライザー メソッドを簡単に作成できます。 これにより、毎回データベースにクエリを実行することなく、アプリケーションの任意のビューまたはテンプレートからユーザーの名前にアクセスできます。
データを読み書きする Django シリアライザーでメソッド フィールドを作成しようとしています。 フィールドは「ステータス」と呼ばれ、ユーザーがアクティブなサブスクリプションを持っている場合は「アクティブ」を返し、そうでない場合は「非アクティブ」を返します。
これが私のコードです:
class UserSerializer(serializers.ModelSerializer):
status = serializers.SerializerMethodField()
def get_status(self, obj):
if obj.subscription_set.filter(is_active=True).exists():
return 'active'
else:
return 'inactive'
class Meta:
model = UserProfile
fields = ('username', 'email', 'first_name', 'last_name', 'status')
def update(self, instance, validated_data):
instance.username = validated_data['username']
instance.email = validated_data['email']
if validated_data['password']: # password can be empty string when updating user profile without changing password (e-mail only) - https://github.com/tomchristie/django-rest-framework/issues/3086#issuecomment-290987912 - thanks @encode! :) # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=line-too-long # noqa E501 (line too long) pylint: disable=C0301 # noqa E501 (line too long) pylint: disable=C0301 # noqa E501 (line too long) pylint: disable=C0301 # noqa E501 (l... instance.set_password(validated_data['password'])
instance.save()
return instance
Postman または Insomnia REST クライアントで PUT 要求を使用してデータを保存しようとすると、次のようなエラーが発生します - "detail": "Method "PUT"" not allowed.""
これは、追加したにもかかわらず発生します update()
上記の私のコードのメソッドは、このような同様のトピックに関する他の SO 投稿で示唆されているように、ここ Django Rest Framework Serializer Method Field Update Issue です。 どんな助けでも大歓迎です! ありがとう! 🙂