从django rest-framework序列化器返回JsonResponse

wyyhbhjk  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(164)

我的问题是如何从REST框架序列化器返回定制的JsonResponse?
我有这个代码的看法:

# 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']

这只是简单地返回用户模型在json中的主键......我如何让它返回一些定制的东西呢?
我想向一个外部API发出请求,并在我的django的响应中发送该外部api的响应。

b1zrtrql

b1zrtrql1#

您可以使用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}'

相关问题