通过在Djang中运行基于条件的查询检索结果

2024-05-19 17:07:14 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有以下两个表格,我用它来写一本在Django的图书馆。你知道吗

class Book(models.Model):
 """Model representing a book (but not a specific copy of a book)."""
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200,null=True)
    summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book",null=True)
    genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
    shelflocation = models.CharField(max_length=10, null=True)
    pages = models.IntegerField(null=True)
    copies = models.IntegerField(null=True,default=1)

另一个BookInstance模型,我在其中维护状态和副本数

class BookInstance(models.Model):
    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4,
                          help_text="Unique ID for this particular book across whole library")
    book = models.ForeignKey('Book',on_delete=models.SET_NULL,null=True)
    due_back = models.DateField(null=True, blank=True)
    borrower = models.ForeignKey('MemberList',on_delete=models.SET_NULL,null=True)

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

所以,如果一本书被借出,那么在上表中状态将被设置为“o”。 我想显示某个特定作者的所有书籍,该作者的书籍已被借出,但仍有副本(在图书模型中以副本形式维护)

我尝试将queryset添加到列表中,但失败了。有没有一种方法可以根据以下查询中的条件进行查询

if book_instance_count < book.copies or book_instance_count == 0:
    bookquery_res = Book.objects.filter(author__icontains=author_name)

    final_book_list = []
    for book in bookquery_res:
        book_instance_count = BookInstance.objects.filter(book_id=book.id).filter(status__exact='o').count()

        if book_instance_count < book.copies or book_instance_count == 0:
            final_book_list.append(list(book))

编辑1

因此,如果一本书的副本数是3,而同一本书的BookInstance数是2,那么我应该显示相应的书。你知道吗

更新

作为一种解决方法,我使用下面的公式,根据作者姓名计算出借的每本书的数量

num_books = Count('bookinstance',filter=Q(bookinstance__status__exact='o'))
result =Book.objects.filter(author__icontains=author_name).annotate(num_books=num_books)

并利用上述结果进一步过滤HTML呈现中的使用条件

(result.copies > result.num_books)


Tags: instancetruemodelmodelscount副本filternull
2条回答

一个选项是带注释的查询,仅显示同时具有可用和借出图书实例的图书:

from django.db import models

Book.objects\
    .annotate(
        on_loan=Coalesce(
            models.Sum(
                models.Case(
                    models.When(
                        bookinstance__status='o',
                        then=1))),
            0),
        available=Coalesce(
            models.Sum(
                models.Case(
                    models.When(
                        bookinstance__status='a',
                        then=1))),
            0))\
    .filter(author__icontains=author_name, on_loan__gt=0, available__gt=0)

你可以阅读^{}^{}和其他的。你知道吗

你把事情弄得太复杂了。您可以在单个查询中直接执行此操作。你知道吗

Book.objects.filter(
    author__icontains=author_name
).filter(
    bookinstance__status="o"
).filter(bookinstance__status="a")

它将找到该作者的所有书籍,其中至少有一个可用实例和一个onloan实例。你知道吗

相关问题 更多 >