Django对象和manyTomany相关,prefetch_related吗?

时间:2019-10-09 20:55:13

标签: django django-models django-templates django-views

我有三种型号:

class Season(models.Model):
    name = models.CharField(max_length=512)

class Clothes(models.Model):
    season = models.ForeignKey(Season, related_name='season_clothes', on_delete=models.CASCADE)
    name = models.CharField(max_length=512)

class User(models.Model):
    name = models.CharField()
    clothes = models.ManyToManyField(Clothes)

如果我知道此请求是哪个用户,如何在模板中获取用户的所有带有季节的衣服。

像这样:

Winter - (It's a Season name)
 Сoat - (name of clothes)
 Scarf - (name of clothes)
 Boots - (name of clothes)

Summer - (It's a Season name)
 Shorts - (name of clothes)
 Swimming trunks - (name of clothes)
 Sneakers - (name of clothes)

2 个答案:

答案 0 :(得分:0)

您可以为User模型创建一种方法来获取相关服装:

class User(models.Model):
    name = models.CharField()
    clothes = models.ManyToManyField(Clothes)

    def get_clothes(self):
        season_name = '' #not sure where this comes from
        return self.clothes.filter(season__name=season_name)

现在,您可以轻松地在模板中访问它们:

{% for cloth in user.get_clothes %}
    <h1>{{ cloth }}</h1>
{% endfor %}

答案 1 :(得分:0)

{% for c in user.clothes.all %}
{% ifchanged c.season %} {{ c.season }} {% endifchanged %}
{{ c }}
{% endfor %}