Django: Link two models with common foreign keys

Viewed 105

Im new to django and im currently making an admin panel where i can view user orders.

I handle my orders based on the following OrderItem Model

class OrderItem(models.Model):
    customer = models.ForeignKey(
        User, on_delete=models.SET_NULL, blank=True, null=True)
    product = models.ForeignKey(
        Product, on_delete=models.SET_NULL, blank=True, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

and their shipping info in the follwing ShippingAdress model

class ShippingAddress(models.Model):
    customer = models.ForeignKey(
        User, on_delete=models.SET_NULL, blank=True, null=True)
    address = models.CharField(max_length=200, null=True)
    city = models.CharField(max_length=200, null=True)
    state = models.CharField(max_length=200, null=True)
    zipcode = models.CharField(max_length=200, null=True)

Views.py

orders=OrderItem.objects.select_related('customer')
 context={
        'orders':orders,        
    }

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

and in my html i want to print each customer's ShippingAdress data. Im thinking something like the following but im stuck and it doesnt work.

{% for order in orders %}

  <td>{{order.customer.address}}</td>
  <td>{{order.customer.city}}</td>

{% endfor %}

What is the correct way to achieve this?

1 Answers

Add related_name to your ShippingAddress

class ShippingAddress(models.Model):
customer = models.ForeignKey(
    User, on_delete=models.SET_NULL, blank=True, null=True, related_name="addresses")

and use it in your template like that

<td>{{order.customer.addresses.first.address}}</td>

with first you get the first address and with all all of them.

Related