如何通过属性从django模型组中选择结果

时间:2017-09-26 22:40:37

标签: django django-templates models manytomanyfield

我需要帮助解决一些我无法用Django解决的问题(除非做蹩脚的嵌套)。

我有这三种模式:

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)

我想在我的模板中打印一个表格,如下所示:

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

相反,我只是设法打印了这个:

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 $   |

在视图中执行此操作:

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

然后在模板中嵌套了两个:

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

我能想到的唯一解决方案是在视图中按数量重新组合优惠,但这意味着很多嵌套,我几乎可以肯定有更好的方法来做我想要的,但我可以找不到解决方案..

任何人都可以帮我吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

使用Serializer Relations这些方面的某些内容可以帮助您以更有效的方式实现目标:

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')