Django:获取有序查询集的值

时间:2013-04-16 11:46:17

标签: django django-queryset

我有一个模特,

class Book(models.Model):
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()

我是根据类别动态订购Book对象,但我也希望得到相应的值。例如,当它们被分类时,我也希望显示相应的价格。

这样做的:

Book.objects.order_by('price').values()

并在模板中

Book: {{ book }} - Price: {{ book.value.2 }} 

工作正常。但是,我想选择哪个字段在运行时可以排序,例如,如果我想按页面排序,我需要传递book.value.1。因此,视图应该传递已排序的字段。像下面这样的东西可以解决我的问题:

{{ book.{{ sortField }} }}

Django发出错误。我该怎么解决这个问题?如何通过该字段以便我可以使用相应的值?

2 个答案:

答案 0 :(得分:2)

简化示例:

<强>模板

<span>Currently ordering by {{ order_by }}</span>
<ul>
    <li><a href="?order_by=price">price</a></li>
    <li><a href="?order_by=pages">pages</a></li>
</ul>
<ul>
    {% for obj in object_list %}
        <li><a href="{{ obj.get_absolute_url }}">{{ obj.name }}</a></li>
    {% endfor %}
</ul>

<强> views.py

class FooListView(ListView):
    allow_ordering_on = ['pk', 'pages', 'price']  # restrictions
    order_by = 'pk'

    def get(self, request, *args, **kwargs):
        order_by = request.GET.get('order_by', self.order_by)

        if order_by in self.allow_ordering_on:
            self.order_by = order_by
            self.object_list = self.model.objects.all().order_by('whatever')
            if not allow_empty and len(self.object_list) == 0:
                raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.")
                              % {'class_name': self.__class__.__name__})
            context = self.get_context_data(object_list=self.object_list)
            return self.render_to_response(context)

        else:
            return super(FooListView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(FooListView, self).get_context_data(**kwargs)
        context['order_by'] = self.order_by
        return context

您可以覆盖get_context_data以添加用于标记当前字段排序的变量。

答案 1 :(得分:0)

在shell上:

books = Book.objects.order_by('price').values()
book = books[0]
print book['price']

因此,在模板中,您应该能够遍历书籍并访问字段:

{% for book in books %}    
    {{ book.price }}
{% endfor %}