Search code examples
djangoone-to-manyreverse-lookup

Django: one-to-many relationship and reverse lookup


i have a Problem which i am unsure what the most django/pythonic way to solve it would be. I have the following models:

class Order(models.Model):
    ord_someinformation = models.CharField(max_length=10)

class Articles(models.Model):
    myFK = models.ForeignKey(Order)
    detail_article= models.CharField(max_length=10)

so every Order can have multiple Order_Details think about it like a shopping basket where i have an Order and within it i have multiple articles.

I want to iterate over the orders and the articles within the template. I thought about something like.

myOrder = Order.objects.("" i have no idea what to put here "")

within the template i thought about something like this:

{% for order in myOrder %}
    {{ order.ord_someinformation }}
    {% for articles in order.articles %}
        {{ detail_article }}
    {% endif %}
{% endif %}

is this possible? If so how ?


Solution

  • I don't know why you think you need to put anything there. You just want to send all the orders to the template, then iterate through them their articles there.

    myOrder = Order.objects.all()
    

    ...

    {% for order in myOrder %}
        {{ order.ord_someinformation }}
        {% for article in order.articles_set.all %}
            {{ article.detail_article }}
        {% endif %}
    {% endif %}