Возврат JsonResponse из сериализатора django rest-framework
Мой вопрос в том, как я могу вернуть пользовательский JsonResponse из сериализатора rest-framework?
У меня есть представление с таким кодом:
# Send money to outside of Pearmonie
class sendmoney_external(viewsets.ModelViewSet):
# Database model
queryset = User.objects.all()
# Serializer - this performs the actions on the queried database entry
serializer_class = SendMoneyExternalSerializer
# What field in database model will be used to search
lookup_field = 'username'
Мой сериализатор выглядит примерно так:
# Serializer for sending money to another Pearmonie user
class SendMoneyExternalSerializer(serializers.ModelSerializer):
# This is the function that runs for a PUT request
def update(self, instance,validated_data):
# Verifies the requesting user owns the database account
if str(self.context['request'].user) != str(instance.username) and not str(self.context['request'].user) in instance.userprofile.banking_write:
raise exceptions.PermissionDenied('You do not have permission to update')
account_number = self.context['request'].data['to_account']
amount = self.context['request'].data['amount']
to_bank = self.context['request'].data['to_bank']
# Creates the order in the database
from_user = BankingTransaction.objects.create(
user = instance,
date = timezone.now(),
from_account_num = instance.userprofile.account_number,
from_account_name = instance.userprofile.company,
to_account = self.context['request'].data['to_account'],
to_bank = to_bank,
amount_transferred = amount,
description = self.context['request'].data['description'],
trans_reference = self.context['request'].data['trans_reference'],
status = self.context['request'].data['status'],
)
instance.userprofile.notification_count += 1
instance.userprofile.save()
# Creates the notification for the supplier in the database
from_notification = Notifications.objects.create(
user=instance,
date=timezone.now(),
read=False,
message=f'You have paid N{amount} to account number {account_number} ({to_bank})'
)
return instance
class Meta:
model = User
fields = ['pk']
Это просто возвращает первичный ключ модели User в json... как мне сделать так, чтобы он возвращал что-то пользовательское?
Я хочу сделать запрос к внешнему api и отправить ответ этого внешнего api в ответ моего django.
Вы можете использовать SerializerMethodField
для пользовательской логики.
class SendMoneyExternalSerializer(serializers.ModelSerializer):
# This is the function that runs for a PUT request
custom_data = serializers.SerializerMethodField()
class Meta:
model = User
fields = ['pk', 'custom_data']
def get_custom_data(self, obj):
# Your coustom logic here. (obj) represent the User object
return f'{obj.first_name} {obj.username}'