Home > Mobile >  how do I render shipping address_one object associated with a specific order
how do I render shipping address_one object associated with a specific order

Time:04-09

So the customer has an order page where I want to render their order details, specifically product name, date ordered, status, and their delivery location, right now I got everything to work except the delivery location("address_one"). I would really appreciate it if someone can help, thx!

models.py

    class Order(models.Model):
        customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    
    class OrderItem(models.Model):
        product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
        order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    
    class Product(models.Model):
        name = models.CharField(max_length=150)
        description = models.TextField()
    
    class ShippingAddress(models.Model):
        customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
        order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
        address_one = models.CharField(max_length=200)

views.py

    @login_required
    def orders(request):
        orderitems = OrderItem.objects.filter(order__customer__user=request.user)

        #how do I get the shipping address associated with order
        shipping = ShippingAddress.objects.filter()

        context = {"orderitems": orderitems, "shipping": shipping}

HTML

        {% for orderitem in orderitems %}
            <div >
                
                <div >{{ orderitem.product.name }}</div>
                <div >{{ orderitem.date_added }}</div>
                <div >dummydata</div>
                <div >{{ shipping.address_one }}</div>

            </div>
        {% endfor %}

enter image description here

CodePudding user response:

Try this:

views.py

@login_required
def orders(request):
   orderitems = OrderItem.objects.filter(order__customer__user=request.user).prefetch_related('order__shippingaddress_set')
   context = {"orderitems": orderitems}

html(template)

{% for orderitem in orderitems %}
    <div >
       <div >{{ orderitem.product.name }}</div>
       <div >{{ orderitem.date_added }}</div>
       <div >dummydata</div>
       <div >{{ orderitem.order.shippingaddress_set.all.0.address_one }}</div>
    </div>
{% endfor %}
  • Related