Babban matsalar filin serializer na karanta rubuta shine ana iya cin zarafinsa cikin sauƙi. Misali, idan kuna da samfurin da ke adana bayanan mai amfani a cikin filin da ake kira “name”, zaku iya ƙirƙirar hanyar serializer cikin sauƙi wanda zai karanta sunan mai amfani daga ma’ajin bayanai kuma a rubuta shi zuwa filin “name” na ƙirar. Wannan zai ba ka damar samun damar sunan mai amfani daga kowane ra'ayi ko samfuri a cikin aikace-aikacenka, ba tare da neman bayanan bayanan kowane lokaci ba.
Ina ƙoƙarin ƙirƙirar filin hanya a cikin serializer na Django wanda zai karanta da rubuta bayanai. Ana kiran filin "status" kuma ina so ya dawo "active" idan mai amfani yana da biyan kuɗi mai aiki, kuma "marasa aiki" idan basu yi ba.
Ga lambara:
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
Kuskuren da nake samu shine wannan lokacin da na yi ƙoƙarin adana bayanan tare da buƙatar PUT a cikin Postman ko Insomnia REST abokin ciniki - "detail": "Method "PUT"" not allowed.""
Wannan yana faruwa ko da yake na ƙara da update()
hanya a cikin lambara ta sama kamar yadda wasu abubuwan SO suka ba da shawara akan batutuwa masu kama da wannan a nan Django Rest Framework Serializer Batun Sabunta Filin. Duk wani taimako za a yaba! Godiya! 🙂