Django объект, связанный и многие Tomany, prefetch_related? - PullRequest
0 голосов
/ 09 октября 2019

У меня есть три модели:

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 голосов
/ 17 октября 2019
{% for c in user.clothes.all %}
{% ifchanged c.season %} {{ c.season }} {% endifchanged %}
{{ c }}
{% endfor %}
0 голосов
/ 10 октября 2019

Вы можете создать метод для вашей модели 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 %}
...