Django在views.py中过滤外键模型

时间:2018-05-16 14:39:48

标签: django django-models django-templates django-views

我有两个模型,一个叫BooksBookInstance,一个Book有很多BookInstance s,

class Books(models.Model):

.........

    def get_absolute_url(self):
        """
        Returns the url to access a detail record for this book.
        """
        return reverse('book-detail', args=[str(self.id)])

    def __str__(self):
        """
        String for representing the Model object.
        """
        return '{0}'.format(self.book_name)
class BookInstance(models.Model):

    books = models.ForeignKey('Books',verbose_name="Books", on_delete=models.SET_NULL, null=True) 
    keyrequest = models.OneToOneField('BookRequest', verbose_name='Book requests', on_delete=models.SET_NULL, null=True, blank=True,)

    LOAN_STATUS = (
        ('a', 'Available'),
        ('o', 'On loan'),
        ('r', 'Reserved'),
    )

    status = models.CharField(max_length=1, choices=LOAN_STATUS, help_text='Key availability', verbose_name="Key status", blank=True)

    date_out = models.DateField(null=True, blank=True, verbose_name="Date Issued")
    due_back = models.DateField(null=True, blank=True, verbose_name="Date to be returned")

......   
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book")

我在views.py中有一个基于类的视图,它使用Book模型显示该图书的BookInstances总数,这是我的views.py:

class KeyListView(generic.ListView):
    model = RoomKey
    fields = '__all__'
    template_name = 'catalog/roomkey_list.html'

我有一个模板,显示BookInstances的所有Book的数量,如下所示:

{{ books.bookinstance_set.all.count }}

但是我想过滤掉它并显示BookInstance可用 Book的数量,我尝试在{{1}中添加查询管理器但是,这不起作用,django从未抛出任何错误,它只是没有显示任何东西。有人可以告诉我实现这样的东西的正确方法吗?

1 个答案:

答案 0 :(得分:1)

您可以覆盖视图的get_queryset()方法,并注释计数:

from django.db.models import Count, Case, When, CharField

def get_queryset(self):
    return Books.objects.annotate(
    available_books_count=Count(Case(
    When(bookinstance__status='a', then=1),
    output_field=CharField(),
))

现在在模板中你可以做

{{ books.available_books_count }}
相关问题