覆盖Django restframework嵌套序列化程序的create方法

时间:2020-03-22 03:47:30

标签: python django django-rest-framework

我正在尝试在Django-rest-framework中使用嵌套的可写序列化程序。当我发送带有以下数据的POST请求时:

library(lubridate)
complete_dataset_1 = complete_dataset
    %>% mutate(age_at_enrollment = time_length(difftime(
        as.Date(start_date, format="%m/%d/%Y"),
        as.Date(birth_date, format="%m/%d/%Y")), "years")

我遇到一个错误:

{
    "acc_name": "Salary Card",
    "acc_type_id": {
        "id": 2,
        "acc_type_name": "Debit Card"
    },
    "credit_amt": null,
    "bill_dt": null,
    "due_dt": null,
    "balance": "0.00",
    "comments": null
}

我实际上为AccountTypes传递了id,但是为什么restframework会自动将其删除?我该如何解决这个问题?如何使用现有帐户类型创建一个新帐户?

观看次数:

Cannot assign "OrderedDict([('acc_type_name', 'Debit Card')])": "Accounts.acc_type_id" must be a "AccountTypes" instance.

型号:

class AccountTypesViewSet(ListAPIView):
    name = __name__
    pagination_class = None
    queryset = AccountTypes.objects.filter(active='Y')
    serializer_class = AccountTypesSerializer


class AccountsViewSet(viewsets.ModelViewSet):
    pagination_class = None
    queryset = Accounts.objects.all()
    serializer_class = AccountsSerializer

序列化器:

class AccountTypes(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
    acc_type_name = models.CharField(max_length=50)
    active = models.CharField(max_length=1, default='Y')

    class Meta:
        db_table = f'"{schema}"."taccount_types"'
        managed = False

class Accounts(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
    acc_name = models.CharField(max_length=1024)
    acc_type_id = models.ForeignKey(
        to=AccountTypes,
        db_column='acc_type_id',
        related_name='accounts',
        on_delete=models.DO_NOTHING
    )
    credit_amt = models.DecimalField(max_digits=11, decimal_places=2, null=True)
    bill_dt = models.DateField(null=True)
    due_dt = models.DateField(null=True)
    balance = models.DecimalField(max_digits=11, decimal_places=2, default=0)
    comments = models.CharField(max_length=1024, null=True)

    class Meta:
        db_table = f'"{schema}"."taccounts"'
        managed = False

1 个答案:

答案 0 :(得分:0)

您不需要设置id字段,因为Django会自行完成,因此请删除以下行:

id = models.AutoField(primary_key=True, editable=False)

接下来,您需要发送id模型的AccountTypes来创建新帐户,然后给Django dict fields = ('id', 'acc_type_name')。它不知道该怎么办。因此,只需发送id作为号码即可。而且您不需要AccountTypesSerializer和那行acc_type_id = AccountTypesSerializer()

接下来,您应该在视图中创建帐户,而不是在序列化程序中创建帐户,创建后必须保存该帐户。