附加在For循环中不起作用

时间:2017-04-28 09:38:44

标签: python django

first_sale_all_menu             = []

for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')):
    link_to_mamapedia_cat   = link_to_home_page + one_product_category.get_absolute_url()
    mamapedia_category_name = one_product_category.name
    if (one_product_category.image_for_top_menu != None):
        header_image = link_to_home_page + one_product_category.main_picture.url  # TODO use thumbnail
    else:
        header_image = ''

    first_sale_all_menu.append({
        'menu_children_url'         : link_to_mamapedia_cat,
        'menu_children_title'       : mamapedia_category_name,
        'menu_product_image_src'    : header_image
    })

不知何故,append()方法不起作用,它仍然是first_sale_all_menu的空列表。

只是为了确保,即使这不起作用:

first_sale_all_menu             = []
for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')):
    link_to_mamapedia_cat   = link_to_home_page + one_product_category.get_absolute_url()
    mamapedia_category_name = one_product_category.name
    if (one_product_category.image_for_top_menu != None):
        header_image = link_to_home_page + one_product_category.main_picture.url  # TODO use thumbnail
    else:
        header_image = ''

    first_sale_all_menu.append({
        'menu_children_url': 'link_to_mamapedia_cat',
        'menu_children_title': 'mamapedia_category_name',
        'menu_product_image_src': 'header_image'
    })

但这有效:

first_sale_all_menu             = []
first_sale_all_menu.append({
        'menu_children_url': 'link_to_mamapedia_cat',
        'menu_children_title': 'mamapedia_category_name',
        'menu_product_image_src': 'header_image'
    })

我不知道为什么,但是append()在我的for循环中不起作用。是的,link_to_mamapedia_cat,mamapedia_category_name,header_image都有字符串值。

好的,我遇到了问题,原来查询从未执行过,错误的模型。哈哈。

1 个答案:

答案 0 :(得分:1)

关键是,非常简单,你的循环还没有被执行。您可以添加要检查的输出。

first_sale_all_menu             = []

for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')):
    print(1)
    link_to_mamapedia_cat   = link_to_home_page + one_product_category.get_absolute_url()
    mamapedia_category_name = one_product_category.name
    if (one_product_category.image_for_top_menu != None):
        header_image = link_to_home_page + one_product_category.main_picture.url  # TODO use thumbnail
    else:
        header_image = ''

    first_sale_all_menu.append({
        'menu_children_url'         : link_to_mamapedia_cat,
        'menu_children_title'       : mamapedia_category_name,
        'menu_product_image_src'    : header_image
    })