[Django]-List not filling properly

2👍

You do not initialize a DisplayProduct, you simply set dp to be a reference to the DisplayProduct class, and as a result, you change fields of the class directly:

for product in product_list:
    p = PricedProduct.objects.filter(proid=product)
    p.order_by('date')


    dp = DisplayProduct()  # construct a new DisplayProduct
    dp.proid = product.id
    dp.proname = product.productname

    print(product.productname)

    dp.proprice = p[0].value
    displaylist.insert(0,dp)

Note that this code is rather inefficient: by inserting at the top, you construct an algorithm with time complexity O(n2). Appending at the end of the list is usually more efficient (since it has amortized cost O(1)). In case you need to reverse the list, it is better to reverse at the end.

I would also advice to construct a proper initializer for DisplayProduct (perhaps your class already has a proper initialzier), so that we can rewrite it to:

for product in product_list:
    p = PricedProduct.objects.filter(proid=product)
    p.order_by('date')

    # might require some changes to the __init__ of DisplayProduct
    dp = DisplayProduct(
        proid=product.id,
        proname=product.productname,
        proprice=p[0].value
    )

    print(product.productname)

    # appending is more efficient than prepending
    displaylist.append(dp)

Leave a comment