你好,我已经被卡住了好几个星期,想知道如何为我正在做的一个项目创建一个订单& 库存系统。我不知道如何正确地问这个问题,但我的问题是当用户向他们的购物车中添加商品时>;我将订单详情存储在mongodb的订单集合中>;然后我需要弄清楚如何从我的库存集合中减去客户订单中的商品数量。如何用mongodb、Python来完成这个任务呢 这是客户下订单时创建的文档
{
"_id": "5eca94b4f56331fd9eade681",
"ordernumber": 343,
"order": {
"order_details": [
{
"customer_info": [
{
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]"
}
],
"shipping_details": [
{
"shipping_address": "Test Address",
"shipping_zip": "12345",
"shippingl_city": "Test city",
"shipping_country": "USA"
}
],
"products_ordered": [
{
"variant_id": "a",
"product_name": "red shirt",
"price": 30,
"quantity": 2,
"image": "imageurl",
"size": "Small"
},
{
"variant_id": "f",
"product_name": "Blue Jeans",
"price": 20,
"quantity": 3,
"image": "imageurl",
"size": "Large"
}
]
}
]
}
}
这些都是我的库存收藏中的产品,我希望库存订单数量减去客户购买的数量。
{
"_id": "5eca0ff4898b8f30a9fee5e5",
"product_id": 1,
"product_name": "red shirt",
"category": "shirts",
"price": 30,
"status": "instock",
"description": "nice red shirt",
"alt": "string",
"images": [
"imageUrl1",
"imageUrl2"
],
"variants": [
{
"Small": [
{
"variant_id": "a",
"inventory": 30
}
],
"Medium": [
{
"variant_id": "b",
"inventory": 10
}
],
"Large": [
{
"variant_id": "c",
"inventory": 10
}
]
}
]
}
{
"_id": "5eca108f898b8f30a9fee5e6",
"product_id": 2,
"product_name": "blue jeans",
"category": "jeans",
"price": 20,
"status": "instock",
"description": "nice blue jeans",
"alt": "string",
"images": [
"ImageURL"
],
"variants": [
{
"Small": [
{
"variant_id": "d",
"inventory": 100
}
],
"Medium": [
{
"variant_id": "e",
"inventory": 150
}
],
"Large": [
{
"variant_id": "f",
"inventory": 70
}
] }
]
}
我建议把它和创建订单的服务一起做。
我还想建议重构一下db结构,因为在更大范围内维护这个结构会比较困难。
因为目前我们将不得不写这样的东西
for ordered_product in products_ordered:
query = { "product_name": ordered_product.get("product_name") }
inventory_product = inventory_collection.find_one(query)
product_id = inventory_product["_id"]
existing_count = inventory_product["variants"][0][ordered_product.size][0]["inventory"]
inventory_product["variants"][0][ordered_product["size"]][0]["inventory"] = existing_count - ordered_product["quantity"]
inventory_collection.update_one({ "_id": product_id }, { "$set": inventory_product })
我已经硬编码了列表的索引值。你可以使用filter()来过滤出你需要的变量和大小。
这段代码在我看来绝对是乱七八糟的.当然你可以重构这段代码,把它拆分成模型文件本身里面的函数,但我建议重构db结构以获得更好的可扩展性。
也许你可以把变体移到一个单独的集合中,并使用product_id作为链接。你必须在开始写代码之前考虑清楚。
希望能帮到你。