0

I need some help with a problem that i can't figure out with Django (unless by doing crappy nested for).

I have these three models :

class Article(models.Model):
    label = models.CharField(max_length=100)
    unity = models.ForeignKey('Unity')
    category = models.ForeignKey('Category')
    user = models.ForeignKey(User)

class Store(models.Model):
    label = models.CharField(max_length=100)
    address = models.TextField()
    products = models.ManyToManyField(Article, through='Offer')
    user = models.ForeignKey(User)

class Offer(models.Model):
    quantity = models.FloatField()
    price = models.FloatField()
    infos = models.TextField(blank=True)
    article = models.ForeignKey('Article')
    store = models.ForeignKey('Store')
    user = models.ForeignKey(User)

I'd like to print a table in my template that would looks like :

Article | Quantity | Infos | Store_1 | Store_2 | Store_n
------- | -------- | ----- | ------- | ------- | -------
Ham     | 4        | Bla   | 4.2 $   | 5.0 $   |
Ham     | 6        | Bla   | 6.0 $   | 7.5 $   |

Instead, i only managed to have print this :

Article | Quantity | Infos | Store_1 | Store_2 | Store_n
------- | -------- | ----- | ------- | ------- | -------
Ham     | 4        | Bla   | 4.2 $   |         |
Ham     | 6        | Bla   | 6.0 $   |         |
Ham     | 4        | Bla   |         | 5.0 $   |
Ham     | 6        | Bla   |         | 7.5 $   |

By doing this in the view :

articles = Article.objects.filter(user=request.user)
for article in articles:
    article.offers = Offer.objects.filter(article=article)

and then two nested for in the template :

{% for article in articles %}
    {% for offer in article.offers %}
        <tr>
           ...
        </tr>
    {% endfor %}
{% endfor %}

The only solution i can think of is to regroup the offers by quantity in the view, but that implies a lot of nested for, and i'm almost sure there is a better way to do what i want, but i can't find the solution..

Can anyone help me with this ? Thanks a lot !

Gemkodor
  • 1
  • 3

1 Answers1

0

Something along these lines using Serializer Relations should help you achieve your goal in a more efficient way:

class OfferSerializer(serializers.ModelSerializer):

    class Meta:
        model = Offer
        fields = ('quantity', 'infos', 'store')


class ArticleSerializer(serializers.ModelSerializer):
    offer = OfferSerializer()

    class Meta:
        model = BlogPost
        fields = ('label', 'offer')
Kyle Higginson
  • 922
  • 6
  • 11
  • If i'm right, ModelSerializer is only available with Django REST Framework which i don't use in my project, is there another way ? – Gemkodor Sep 27 '17 at 10:43