0

I'm new in django, I would like to display my view.py to index.html,

the view.py:

def index(request):
context_dict = {}

customers = Customer.objects.all()
carts = Cart.objects.select_related('customer')
goods = Good.objects.select_related('cart__customer')

context_dict['Cart']=carts
context_dict['Good']=goods
context_dict['Customer'] = customers

return render(request, 'index.html', context=context_dict)

and the index.html for loop is like this:

<ul>
            {% for customer in Customer %}
                <li>{{ customer.name }}</li>
                {% for cart in Cart %}
                    {% if customer.id == cart.id %}
                        {% for good in Good %}
                            {% if cart.id == good.id %}
                                {{good.name}}--{{good.count}}--{{good.price}}
                            {% endif %}
                        {% endfor %}
                    {% endif %}
                {% endfor %}
            {% endfor %}

        </ul>

but the result displayed like this:

result

Bob should have water--2--50 under it. it seems customer.id == cart.id cannot match. but I don't know how to fix it. please help, thanks a lot!

1 Answer 1

1
  1. customer.id should match card.customer_id and so on (cart.good_id == good.id)
  2. if you have a single cart with a single good in it your solution will still return all of the customers, all of the goods to show a single line on the page - this is not really a good solution.

So try using joins and retrieve only needed data, e.g.:

actual_carts = Cart.objects.all().select_related('customer', 'good').order_by('customer_id', )

This will return only customers and goods mentioned in carts. select_related will let you access all the needed info from customers as well as from goods.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.