How to comment out multiple django models

I have the following Django models:

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 model is UserBook

used to indicate whether the user owns the book.

Now I want to return a list of all book categories, ordered by the number of most popular books (i.e. the most popular categories should appear first).

I tried with the Django ORM annotations, but I didn't get it to work.

This is a subquery that doesn't work:

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

      

(resulting in an error message

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

      

I know that the order_by clause is still missing from this subquery, but my guess is that I need to execute the subquery first.

Do you know what question I can solve this problem with in django? I want not to split it into multiple queries or do any calculations in django.

+3


source to share


1 answer


You can use it RawSQL('any raw expression', ())

as a workaround.



0


source







All Articles