Django Rest 框架 - “此字段是必填字段。”

发布于 2025-01-10 23:02:14 字数 1991 浏览 0 评论 0原文

我有两个类,类 Amount 和 Transaction

class Account(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
account_number = models.BigIntegerField(unique=True)
currency = models.CharField(max_length=3)
balance = models.DecimalField(max_digits=20, decimal_places=2, default=0)


class Transaction(models.Model):
sender_account_number = models.BigIntegerField()
recipient_account_number = models.BigIntegerField()
amount = models.DecimalField(max_digits=20, decimal_places=2)
date_creation = models.DateTimeField(auto_now_add=True)
account = models.ForeignKey(Account, on_delete=models.CASCADE)

我的序列化器:

class TransactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Transaction
        fields = ['sender_account_number', 'recipient_account_number', 'amount', 'date_creation', 'account']
        extra_kwargs = {
            'date_creation': {'read_only': True},

        }``

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ['id', 'account_number', 'currency', 'balance', 'user']
        extra_kwargs = {
            'balance': {'read_only': True},
            'user': {'read_only': True},
        }

我想向数据库添加一项交易,但这样它会根据帐号自动设置我的 account_id,因为一个用户可以拥有多个帐户*。 我尝试了perform_create方法

def perform_create(self, serializer):
    serializer.save(account=Account.objects.values('id').filter(
        account_number=self.request.data['sender_account_number']))

但失败了。我收到错误

{
"account": [
    "This field is required."
]

}

例如,我想发送这些数据

{

"sender_account_number": 346,
"recipient_account_number": 546,
"amount": 60

}

和Post方法:

def post(self, request):   
    serializer = TransactionSerializer(data=request.data)
    serializer.is_valid(raise_exception=True):
    return Response(serializer.data)
 

如何解决?

I have two classes, class Amount and Transaction

class Account(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
account_number = models.BigIntegerField(unique=True)
currency = models.CharField(max_length=3)
balance = models.DecimalField(max_digits=20, decimal_places=2, default=0)


class Transaction(models.Model):
sender_account_number = models.BigIntegerField()
recipient_account_number = models.BigIntegerField()
amount = models.DecimalField(max_digits=20, decimal_places=2)
date_creation = models.DateTimeField(auto_now_add=True)
account = models.ForeignKey(Account, on_delete=models.CASCADE)

My serializers:

class TransactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Transaction
        fields = ['sender_account_number', 'recipient_account_number', 'amount', 'date_creation', 'account']
        extra_kwargs = {
            'date_creation': {'read_only': True},

        }``

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ['id', 'account_number', 'currency', 'balance', 'user']
        extra_kwargs = {
            'balance': {'read_only': True},
            'user': {'read_only': True},
        }

I want to add a transaction to the database, but so that it automatically sets my account_id based on the account number, because one user can have multiple accounts*.
I tried the perform_create method

def perform_create(self, serializer):
    serializer.save(account=Account.objects.values('id').filter(
        account_number=self.request.data['sender_account_number']))

but I failed. I get error

{
"account": [
    "This field is required."
]

}

for example, I want to send these data

{

"sender_account_number": 346,
"recipient_account_number": 546,
"amount": 60

}

and Post method:

def post(self, request):   
    serializer = TransactionSerializer(data=request.data)
    serializer.is_valid(raise_exception=True):
    return Response(serializer.data)
 

How to solve it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩动你心 2025-01-17 23:02:14

您必须告诉您的交易序列化器该帐户是外键。因此,它需要一个对象而不是字符串。
像这样添加 account = serializers.StringRelatedField()

class TransactionSerializer(serializers.ModelSerializer):
        account = serializers.StringRelatedField()
        class Meta:
            model = Transaction
            fields = ['sender_account_number', 'recipient_account_number', 'amount', 'date_creation', 'account']
            extra_kwargs = {
                'date_creation': {'read_only': True},
    
            }``

如果这样做,则不需要执行创建功能。序列化程序应该会自动为您添加它。您只需从您的帐户模型中检索带有您的帐号的实例。然后在检查序列化器是否有效后将其传递给serializer.save()。像这样

def post(self, request):
    account_number = request.data.get('sender_account_number')
    account = Account.objects.get(account_number=account)
    serializer = TransactionSerializer(data=request.data)
    serializer.is_valid(raise_exception=True):
        serializer.save(account = account_number)
    return Response(serializer.data)

you have to tell your transaction serializer that account is a foreign key. And hence, it would expect an object instead of a string.
add account = serializers.StringRelatedField() like so

class TransactionSerializer(serializers.ModelSerializer):
        account = serializers.StringRelatedField()
        class Meta:
            model = Transaction
            fields = ['sender_account_number', 'recipient_account_number', 'amount', 'date_creation', 'account']
            extra_kwargs = {
                'date_creation': {'read_only': True},
    
            }``

You do not need the perform create function if you do that. serializer should automatically add it for you. you just have to retrieve from your account models, the instance with your account number. then pass it into the serializer.save() after checking if serializer is valid. like so

def post(self, request):
    account_number = request.data.get('sender_account_number')
    account = Account.objects.get(account_number=account)
    serializer = TransactionSerializer(data=request.data)
    serializer.is_valid(raise_exception=True):
        serializer.save(account = account_number)
    return Response(serializer.data)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文