我有这段代码:
for product_code in product_codes:
product_categories = []
product_belongs_to = []
get_categories = """SELECT * FROM stock_groups_styles_map WHERE stock_groups_styles_map.style ='%s'""" % (product_code,)
for category in sql_query(get_categories):
if {product_code: category[1]} in product_categories:
pass
else:
product_categories.append({product_code: category[1]})
for category in product_categories:
category_group = get_group(category.values()[0])
if category_group:
category_name = category_group.replace("-", " ").title()
if category_name:
if category_name == "Vests":
product_belongs_to.append(get_category_ids("Tanks"))
else:
cat_value = get_category_ids(category_name)
if cat_value:
cat_id = get_category_ids(category_name)
product_belongs_to.append(cat_id[0])
ccc_products = {
'_id': ObjectId(),
'collectionId': collectionId,
'categoryIds': product_belongs_to,
'visible' : 'true',
}
products.save(ccc_products)
当我看到mongdb集合时,我有:
{
"_id" : ObjectId("53aaa4e1d901f2430f25a6ba"),
"collectionId" : ObjectId("53aaa4d6d901f2430f25a604"),
"visible" : "true",
"categoryIds" : [
ObjectId("53aaa4d6d901f2430f25a5fc"),
ObjectId("53aaa4d3d901f2430f25a5f9")
]
}
这是正确的,但如果我在product_belongs_to
列表中只有一个项目,我会得到:
{
"_id" : ObjectId("53aaa4e1d901f2430f25a6bd"),
"collectionId" : ObjectId("53aaa4d6d901f2430f25a604"),
"visible" : "true",
"categoryIds" : [
[
ObjectId("53aaa4d6d901f2430f25a5fe")
]
]
}
基本上,"categoryIds"
是包含array
array
解决此问题的唯一方法是执行以下操作:
if len(product_belongs_to) == 1:
product_belongs_to = product_belongs_to[0]
我错过了什么?
任何建议都非常感激。
答案 0 :(得分:1)
我怀疑这一行是有问题的:
product_belongs_to.append(get_category_ids("Tanks"))
get_category_ids
正在返回您要附加到product_belongs_to
的列表。
您可能希望合并结果,以便它们包含唯一值:
product_belongs_to = list(set(product_belongs_to + get_category_ids("Tanks")))