How To Access Foreign Key In A Django Template? (detailview)
Solution 1:
As they are related by OneToOneField, then you can access the values of shop from campaign details view like this:
{{ obj.shop }}
And if you want to access the products, then do it like this:
{{ obj.shop.product.title }}
{{ obj.shop.product.price }}
{{ obj.shop.product2.title }}
{{ obj.shop.product2.price }}
{{ obj.shop.product3.title }}
{{ obj.shop.product3.price }}
Update
Well, in that case I would recommend using ManyToMany relation between Product and Shop. So that, a product can be assigned to multiple shops, or a shop can be assigned to multiple product. Then you can define the relation like this:
classShop(models.Model):
products = models.ManyToManyField(Product)
and if you want iterate through products for a shop, you can do it like this:
{% for product in obj.shop.products.all %}
{{ product.title }}
{{ product.name }}
{% endfor %}
Solution 2:
Your models are wrong anyway, but especially if you want to use a for loop. You don't need the OneToOneFields from Shop to Product, you just want one ForeignKey from Product to Shop.
class Product(models.Model):
shop = models.ForeignKey('Shop')
Now you can do:
{% for product in obj.shop.product_set.all %}
{{ product.title }}
{{ product.price }}
{% endfor %}
If you don't have any other fields on Shop at all, then you can delete that whole model and have the ForeignKey point directly at Campaign, then iterate over obj.product_set.all
.
Post a Comment for "How To Access Foreign Key In A Django Template? (detailview)"