使用Django棉花糖插入外键

时间:2020-10-20 07:35:09

标签: python python-3.x django marshmallow

serializer.py

class ClientSerializer(Schema):
    id = fields.Integer()
    name = fields.String(required=True, validate=lambda x: len(x) > 0)
    created_at = fields.DateTime()
    updated_at = fields.DateTime()


class ProjectSerializer(Schema):
    id = fields.Integer()
    name = fields.String(required=True, validate=lambda x: len(x) > 0)
    project_type = EnumField(ProjectType, by_value=True)
    status = EnumField(ProjectStatus, by_value=True)
    client = fields.Nested(ClientSerializer(), dump_only=True)

views.py

project_serializer = ProjectSerializer(data=request.data)
 project_serializer.is_valid(raise_exception=True)

请求

{
    "name": "Test 1",
    "client": "Test Client"
}

models.py

class Project(TenantBaseModel):
    name = models.TextField()
    project_type = EnumChoiceField(ProjectType, choice_builder=attribute_value)
    status = EnumChoiceField(ProjectStatus, choice_builder=attribute_value, default=ProjectStatus.CREATED)
    client = models.ForeignKey(Client, on_delete=models.PROTECT)

我已经使用Django admin创建了一个名为“ Test Client”的客户端。我尝试传递ID,但似乎没有任何方法代替客户端名称。我收到以下错误消息,

{'client': [ErrorDetail(string='Unknown field.', code='invalid')]}

0 个答案:

没有答案