简体   繁体   English

如何注释多个django模型

[英]How to annotate over multiple django models

I have the following Django models: 我有以下Django模型:

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

    class Meta:
        db_table = "books"

class BookCategory(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)

    class Meta:
        db_table = "bookcategories"

class BookCategoryMembership(models.Model):
    id = models.AutoField(primary_key=True)
    category = models.ForeignKey(BookCategory)
    book = models.ForeignKey(Book)

    class Meta:
        db_table = "bookcategories_books"

class UserBook(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
    book = models.ForeignKey(Book)

    class Meta:
        db_table = "user_book"

The UserBook model is used to denote if a user owns a book. UserBook模型用于表示用户是否拥有书籍。

Now, I want to return the list of all book categories, ordered by the number of most owned books (ie the most popular categories should come up first). 现在,我想返回所有图书类别的列表,按照大多数拥有的图书的数量排序(即最热门的类别应该首先出现)。

I tried with Django ORM annotations, but I did not get it to work. 我尝试使用Django ORM注释,但我没有让它工作。

This is the subquery which does not work: 这是子查询不起作用:

BookCategoryMembership.objects.annotate(num_books=Count("book__userbook")).
values('category_id').annotate(Sum('num_books'))

(resulting in the error message (导致错误消息

FieldError: Cannot compute Sum('num_books'): 'num_books is an aggregate"

I know that from this subquery, the order_by clause is still missing, but I assume I have to get the subquery to work first. 我知道从这个子查询中,order_by子句仍然缺失,但我认为我必须首先使用子查询。

Do you know with which query I can solve this problem in django? 你知道在django我可以用哪个查询来解决这个问题吗? I want to avoid splitting it up into multiple queries or doing any computations in django. 我想避免将它分成多个查询或在django中进行任何计算。

您可以使用RawSQL('any raw expression', ())作为解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM