0

我尝试使用以下语句用 django 创建一个 COUNT GROUP BY

top_book = Borrow.objects.filter(beginDate__gte=str(weekAgoDate)).values('book').order_by().annotate(num_borrow=Count('book')).order_by('-num_borrow')[:5]

但是当我尝试访问模板中的数据时,它没有给出任何输出

{% for cont in top_book %}        
<tr>
<td><a href="/toplibrary/bookInfo/{{ cont.book.idBook }}/">{{ cont.book.title }}</a></td><td>{{ cont.book.isbn }}</td><td>{{ cont.book.author }}</td><td>{{ cont.book.editor }}</td>    

</tr>{% endfor %}

所以我尝试用 Book 类做一个 IN 语句来获取我需要的关于我的书的所有信息

top_books=Book.objects.filter(idBook__in=top_book) 

但我得到这个错误

"This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'"

有人可以提出解决方案吗?

class Book(models.Model):
    idBook = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=255)
    isValid = models.BooleanField(default=True)
    linkDescr = models.CharField(max_length=255)
    editor = models.CharField(max_length=255)
    author = models.CharField(max_length=255)
    isbn = models.BigIntegerField()
    categories = models.ManyToManyField(Category, verbose_name="Categories")
    position = models.ForeignKey(Position, verbose_name="Position")
    addedDate = models.DateTimeField()

class Borrow(models.Model):
    beginDate = models.DateField()
    renewed = models.BooleanField(default=False)
    user = models.ForeignKey(User, verbose_name="BorrowHasUser")
    book = models.ForeignKey(Book, verbose_name="BorrowHasBook")
    returnDate = models.DateField(blank=True, null=True)
4

1 回答 1

0

等等,你是不是想得到借得最多的书?

也许这会更有意义:

top_book = Book.objects.annotate(num_borrow=Count('borrow')).order_by('-num_borrow')[:5]

如果您的领域related_name有一套,请Borrow.book使用它而不是borrow.

 

抱歉,我先在自动驾驶仪上回答。

于 2013-01-16T23:14:52.243 回答