我有两个模型,一个叫Books
和BookInstance
,一个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从未抛出任何错误,它只是没有显示任何东西。有人可以告诉我实现这样的东西的正确方法吗?
答案 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 }}