我有一个如下所示的嵌套数据库模型、一个相应的 Marshmellow Schema 和一个 Flask Restful 资源。
如何使用 POST 请求将嵌套的 Contract(以及嵌套的 ContractComponent 等)对象添加到数据库中?
# Sql Alchemy Model(s)
Customer
- name, address ...
- contracts
Contract
- Contract Components
- MonthlyRecurringCharges
- ..
# Marshmellow Schema
class CustomerSchema(ma.Schema):
class Meta:
fields = ("id", "name", "grouptag", "country",
"segment", "status", "contracts", "created_on")
model = Customer
contracts = ma.Nested(ContractSchema, many=True)
# Flask Restful Resource extract
CustomerListResource(Resource)
if Customer.find_by_name(request.json['name']) == None:
c_name = request.json["name"]
c_contracts = request.json.get("contracts", None)
c_grouptag = request.json.get("grouptag", None)
c_segment = request.json.get("segment", None)
c_status = request.json.get("status", None)
c_country = request.json.get("country", None)
new_customer = Customer(
name=c_name,
contracts=c_contracts,
grouptag=c_grouptag,
segment=c_segment,
status=c_status,
country=c_country
)
db.session.add(new_customer)
db.session.commit()
return customer_schema.dump(new_customer)
如果我发送以下请求,我会收到一个 AttributeError
AttributeError:“dict”对象没有属性“_sa_instance_state”
{
"name": "xyz",
"segment": "Grocery",
"id": 1,
"status": "Active",
"created_on": "2022-01-24T07:36:33",
"grouptag": null,
"contracts": [
{
"created_on": "2022-01-24T07:36:33.768153",
"customer_id": 1,
"id": 1,
"components": [...]
},
}