如何在Django Rest Framework中保存具有一对一关系的模型

时间:2019-01-23 11:28:28

标签: django django-models django-rest-framework django-serializer

我有一个名为BankDetail的Django模型,它与User具有一对一的关系。

#BankeDetails
class BankDetail(models.Model):
    account_holder_name = models.CharField(max_length=100)
    account_number = models.CharField(max_length=50, blank=True, null=True)
    iban = models.CharField("IBAN", max_length=34, blank=True, null=True)
    bank_name = models.CharField(max_length=100)
    bank_address = models.CharField(max_length=500)
    swift_bic_code = models.CharField(max_length=11)
    user = models.OneToOneField(MyUser,on_delete=models.CASCADE)
    accepting_fiat_currency = models.OneToOneField(AcceptedFiatCurrency)
    created_at = models.DateTimeField(auto_now_add=True,null=True)
    updated_at = models.DateTimeField(auto_now=True)

序列化器如下所示:

class BankDetailSerializer(serializers.ModelSerializer):
    """Serializer for BankDetails"""
    class Meta:
        model = BankDetail
        fields = "__all__"

    def validate(self, data):
        if data['account_number'] or data['iban']:
            raise serializers.ValidationError("Please fill Account Number or IBAN")
        return data

请求有效载荷:

{
    "account_holder_name":"Aladin",
    "account_number":"1239893",
    "bank_name":"Aladin Bank",
    "bank_address":"Republic of Wadia",
    "swift_bic_code":"1",
    "user_id":"1",
    "accepting_fiat_currency_id":"1"
}

现在,当我尝试从视图中保存模型时,出现以下错误:

{
    "user": [
        "This field is required."
    ],
    "accepting_fiat_currency": [
        "This field is required."
    ]
}

如何传递这些对象的引用,是否需要使用ID从数据库中手动检索它们?

3 个答案:

答案 0 :(得分:0)

请在序列化器中定义一个相关的模型字段。并且不要使用__all__而不是显式地写入所有字段。这是我的建议:)

您应该在以下问题中找到答案:

Post from StackOverflow

That helped me last week

DRF documentation about Serializer relations

答案 1 :(得分:0)

一种解决方案是使用不同的序列化程序在数据库中创建/检索数据。

用于创建的序列化器应类似于-

class BankDetailSerializer(serializers.ModelSerializer):
"""Serializer for BankDetails"""
    class Meta:
        model = BankDetail
        exclude = ('user', 'accepting_fiat_currency', ) # Note we have excluded the related fields

    def validate(self, data):
        if data['account_number'] or data['iban']:
            raise serializers.ValidationError("Please fill Account Number or IBAN")
        return data 

然后在保存序列化程序时,传递上面两个排除的字段。喜欢-

serializer = BankDetailSerializer(data=request.data)
if serializer.is_valid():
    serializer.save(user=request.user, accepting_fiat_currency=<AcceptedFiatCurrency-object>)
  

如果您在DRF中使用Generic Views,那么我建议您看一下   放入 perform_create 方法。

答案 2 :(得分:0)

您需要发送 "user":"1"。而不是 "user_id":"1"。与其他"accepting_fiat_currency"

相同