如何从数据库中填写列表?

时间:2017-04-29 16:12:24

标签: python django django-templates django-views

我需要将每个别名绑定到其评级,然后将其显示在模板中,并通过减少订购产品。我怎么能这样做?

class Items(models.Model):
    name = models.CharField(max_length=15, verbose_name='Название товара', default='')
    price = models.IntegerField(default=0, verbose_name='Цена')
    # image = models.CharField(max_length=255, verbose_name='Картинка', default='')
    image = models.ImageField(null=True, blank=True, upload_to='image/', verbose_name='Изображение')
    alias = models.SlugField(verbose_name='Alias товара', default='')
    rating = models.FloatField(default=0, verbose_name='Рейтинг')



def popular(request):
    title = 'Популярные'
    products = Items.objects.all()
    category = Category.objects.all()

    context = {
        'products': products,
        'category': category,
        'title': title,
    }
    return render(request, 'popular/main.html', context)

1 个答案:

答案 0 :(得分:0)

您可以按照自己的方式订购数据库中的结果集:

products = Items.objects.order_by('-rating')

在模板中:

{% for product in products %}
    {{product.alias}} - {{product.rating}}
{% endfor %}