解析模板中的查询集

时间:2017-02-20 02:18:28

标签: python django django-templates django-views

大家都有一个结构对象

userfavs  = UserFavs.objects.filter(
        user_id=self.request.user.id)
  • userfavs
    • 菜(id = 3)
      • shop(id = 1)
    • 菜(id = 30)
      • shop(id = 2)
    • 菜(id = 5)
      • shop(id = 1)
    • 菜(id = 15)
      • shop(id = 2)

在模板中我应该

  • 商店(1) - 商店(2)
    • 菜肴(3) - 菜肴(15)
    • 菜肴(5) - 菜肴(30)

我无法理解如何重新组合查询集以获得所需的结果? 你可以帮帮我吗?

class UserFavs(models.Model):
    user = models.ForeignKey(RegModel, verbose_name=u'Пользователь',
                             related_name="userreg", null=True)
    dish = models.ForeignKey(Dish, verbose_name=u'Блюдо',
                             related_name="favsdish", null=True)


class Dish(models.Model):

criterion_list = (
    ('1', u'Блюдо без мяса'),
    ('2', u'Острое блюдо'),
    ('3', u'Здоровое питание'),
    ('4', u'Акция'),
    ('5', u'Блюдо сезона'),
    ('6', u'Блюдо дня'),
    ('7', u'Ваше любимое блюдо'),
    ('8', u'Еда за баллы'))

name = models.CharField(max_length=255, verbose_name=u'Название')
criterion_first = models.CharField(max_length=255, blank=True,
                                   null=True,
                                   choices=criterion_list,
                                   verbose_name=u'Критерий 1')

criterion_second = models.CharField(max_length=255, blank=True,
                                    null=True,
                                    choices=criterion_list,
                                    verbose_name=u'Критерий 2')

price = models.FloatField(max_length=255, verbose_name=u'Цена',
                          default=0, blank=True, null=True)
weight = models.CharField(max_length=255, verbose_name=u'Вес',
                          blank=True, null=True)
description = models.TextField(max_length=3000,
                               verbose_name=u'Описание',
                               blank=True, null=True)
points_price = models.IntegerField(verbose_name=u'Цена за баллы',
                                   default=0, blank=True, null=True)
is_points = models.BooleanField(verbose_name=u'Еда за баллы',
                                default=False, blank=True)
is_recom = models.BooleanField(verbose_name=u'В рекомендациях?',
                               default=True, blank=True)
sale = models.IntegerField(verbose_name=u'Скидка',
                           blank=True, null=True)
is_active = models.BooleanField(verbose_name=u'Блюдо активно?',
                                default=True, blank=True)
shop = models.ForeignKey(Shop, verbose_name=u'Заведение',
                         related_name="dishshop")

def __unicode__(self):
    return u'%s' % (self.name)


class Shop(models.Model):
name = models.CharField(max_length=255, verbose_name=u'Название')
time_begin = models.TimeField(max_length=255,
                              verbose_name=u'Время начала работы')
time_end = models.TimeField(max_length=255,
                            verbose_name=u'Время окончания работы')
phone = models.CharField(max_length=255, verbose_name=u'Телефон')
preview = models.FileField(upload_to='files/shop/preview')
delivery_price = models.IntegerField(verbose_name=u'Стоимость доставки')
min_order = models.IntegerField(verbose_name=u'Минимальный заказ')
del_wait_time = models.IntegerField(verbose_name=u'Время доставки минут')
is_always = models.BooleanField(verbose_name=u'Круглосуточно?',
                                default=True, blank=True)
is_cash = models.BooleanField(verbose_name=u'Наличными',
                              default=True, blank=True)
is_card = models.BooleanField(verbose_name=u'Картой курьеру',
                              default=True, blank=True)
is_online = models.BooleanField(verbose_name=u'Онлайн-оплата',
                                default=True, blank=True)
is_points = models.BooleanField(verbose_name=u'Еда за баллы',
                                default=True, blank=True)
notification = models.CharField(max_length=255,
                                verbose_name=u'Важное уведомление',
                                blank=True, null=True)
email = models.CharField(max_length=255, verbose_name=u'E-mail')
rate = models.FloatField(max_length=255, verbose_name=u'Рейтинг')
destination = models.CharField(max_length=255,
                               verbose_name=u'Местоположение')
specific = models.CharField(max_length=255,
                            verbose_name=u'Специализация ресторана')
description = models.TextField(max_length=3000,
                               verbose_name=u'Описание')
cook = models.CharField(max_length=255, verbose_name=u'Имя повара')
image_cook = models.FileField(upload_to='files/shop/cook')
desc_cook = models.TextField(max_length=3000,
                             verbose_name=u'Описание повара')
shoptype = models.ForeignKey(ShopType, verbose_name=u'Тип заведения',
                             related_name="shop")
slider = models.ForeignKey(Slider, verbose_name=u'Слайдер',
                           related_name="slider")
def __unicode__(self):
    return u'%s' % (self.name)

1 个答案:

答案 0 :(得分:1)

要在商店中进行分组,您可以使用django group on other properties。 在你的情况下,它将是:

{% regroup userfavs by dish.shop as user_favourites %}
{% for item in user_favourites %}
    <span class="one_col">
        {{ item.grouper }} ({{ item.grouper.id }}) {% if not forloop.last %} - {% endif %}
    </span>
{% endfor %}
{% for item in user_favourites %}
    <span class="one_col">
        {% for userfav in item.list %}
            {{ userfav.dish }} ({{ userfav.dish.id }}) {% if not forloop.last %} - {% endif %}
        {% endfor %}
    </span>
{% endfor %}

您需要为班级设置CSS规则&#34; one_col&#34;满足您的设计要求,这不是问题的一部分。