Django在基于类的通用列表视图中过滤子对象

时间:2013-12-19 17:13:43

标签: django foreign-key-relationship django-class-based-views

大家好日子!

我的应用使用基于django类的通用列表视图。我有两个模型对象:通过外键链接的图书和发布者(下面的代码)。我想使用ListView向发布商展示他们的图书,但过滤图书(仅获取当前用户拥有的有效图书)

其他信息:如果可能的话,我不想在模板中使用过滤器。 附加信息2:我不能在模型类中使用过滤器,因为我需要访问请求对象

models.py

class Publisher(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    name = models.CharField(max_length=255)
    active = models.BooleanField(default=True)
    publisher = models.ForeignKey(Publisher, related_name='books')
    owner = models.ForeignKey(User)

views.py

class ListBooksByPublisher(ListView):
    model = Publisher
    template_name = 'list.html'
    context_object_name = 'books'

list.html

{% for publisher in publishers %}
    {{ publisher.name }}
    {% for book in publisher.books.all %}
        {{ book.name }}
    {% endfor %}
{% endfor %}

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:7)

您需要覆盖视图上的get_queryset方法以返回自定义查询集

例如:

class ListBooksByPublisher(ListView):
    ....
    def get_queryset(self):
        return self.model.objects.filter(blablabla))

希望这有帮助

答案 1 :(得分:0)

您可以编写自定义过滤器,该过滤器会返回发布商的图书清单。

yourapp / templatetags / my_filters.py:

from django import template
register = template.Library()

@register.filter
def get_books(publisher):
    return publisher.book_set.filter(YOUR_CUSTOM_FILTER)

您的模板:

{% load get_books from my_filters %}
...
{% for publisher in publishers %}
    {{ publisher.name }}
    {% for book in publisher|get_books %}
        {{ book.name }}
    {% endfor %}
{% endfor %}

另一种方法是将额外数据传递给您的视图:

class ListBooksByPublisher(ListView):
    ...
    def get_context_data(self, **kwargs):
        context = super(ListBooksByPublisher, self).get_context_data(**kwargs)
        context['publishers_with_books'] = your_custom_data_structure
        return context

答案 2 :(得分:-2)

#views
class ListBooksByPublisher(ListView):
    model = Publisher
    template_name = 'list.html'
    context_object_name = 'publishers'
#tmp
{% for publisher in publishers %}
    {{ publisher.name }}
    {% for book in publisher.book_set.all %}
        {{ book.name }}
    {% endfor %}
{% endfor %}