带有注释的 Django 查询集
Django Queryset with annotate
我正在 Django Manager 模型中编写一个方法。
我想编写一个方法来找出每个作者的所有已售出的副本(书籍)的数量。
我在Manager中写了两个模型和方法。
我的问题是该方法也应该可以从任何 Author 查询集中链接,例如
Author.objects.filter(...).exlucde(...).total_copies_sold()
应该也可以。
示例:
author = Author.objects.create(...)
Book.objects.create(..., author=author, copies_sold=10)
Book.objects.create(..., author=author, copies_sold=20)
author_total_books = Author.objects.total_copies_sold().first()
>>> author_total_books.copies
30
在我的代码下面。它像上面的例子一样工作,但后来我尝试了类似的东西:
author_books = Author.objects.filter(id=2).total_copies_sold()
我得到了
'QuerySet' object has no attribute 'annotate'
class AuthorManager(models.Manager):
def total_copies_sold(self):
return self.get_queryset().annotate(copies=Sum('book__copies_sold')
class Author(models.Model):
first_name = models.CharField(max_length=120)
last_name = models.CharField(max_length=120)
objects = AuthorManager()
class Book(models.Model):
title = models.CharField(max_length=120)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
[已编辑]
谢谢 schillingt 的回复。我补充说:
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
return self.annotate(copies=Sum('books__copies_sold'))
我试过类似的东西:
author_books = Author.objects.filter(id=2).total_copies_sold()
>>> author_books.copies
我得到了
'AuthorQueryset' object has no attribute 'copies'
您需要使用Manager.from_queryset
来设置您的管理员。这是 docs.
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
...
class Author(models.Model):
objects = models.Manager.from_queryset(AuthorQueryset)()
您正在寻找的是:
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('books__copies_sold'))
class Author(models.Model):
objects = AuthorManager()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
现在可以链接查询,例如:
author_total_books = Author.objects.total_copies_sold().first()
但是您将无法在 QuerySet 对象上使用它,例如:
author_books = Author.objects.filter(id=2).total_copies_sold()
那是因为您注释的是 Author 对象,而不是 QuerySet。要获得该结果,您应该执行:
Author.objects.annotate_with_copies_sold().get(id=2)
author.copies_sold
15
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
# Write your solution here
return self.annotate(copies_sold=Coalesce(Sum('books__copies_sold'), 0))
class Author(models.Model):
# Make sure this manager is available.
objects = AuthorManager()
# objects = models.Manager.from_queryset(AuthorQuerySet)()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
enter code here
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('Book_Author__copies_sold'))
class Author(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
objects = AuthorManager()
class Meta:
verbose_name_plural = "Author"
verbose_name = 'Author'
ordering = ('first_name','last_name')
class Book(models.Model):
title = models.CharField(max_length=250, unique=True)
copies_sold = models.PositiveIntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='Book_Author')
class Meta:
verbose_name_plural = "Book"
verbose_name = 'Book'
ordering = ('title','copies_sold')
from vehicles.models import Author, Book
try:
author = Author.objects.get(first_name='Mark', last_name='Twain')
except Author.DoesNotExist:
author = Author.objects.create(first_name='Mark', last_name='Twain')
try:
book = Book.objects.get(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
pass
try:
book = Book.objects.get(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
pass
author = Author.objects.annotate_with_copies_sold().first()
print(author.copies_sold)
11
1.Create AuthorManager, AuthorQuerySet classes from Author and Books
2.Create Author, Book models
3.Prepare Test Data and use model manager to filter the queryset
我正在 Django Manager 模型中编写一个方法。 我想编写一个方法来找出每个作者的所有已售出的副本(书籍)的数量。
我在Manager中写了两个模型和方法。 我的问题是该方法也应该可以从任何 Author 查询集中链接,例如
Author.objects.filter(...).exlucde(...).total_copies_sold()
应该也可以。
示例:
author = Author.objects.create(...)
Book.objects.create(..., author=author, copies_sold=10)
Book.objects.create(..., author=author, copies_sold=20)
author_total_books = Author.objects.total_copies_sold().first()
>>> author_total_books.copies
30
在我的代码下面。它像上面的例子一样工作,但后来我尝试了类似的东西:
author_books = Author.objects.filter(id=2).total_copies_sold()
我得到了
'QuerySet' object has no attribute 'annotate'
class AuthorManager(models.Manager):
def total_copies_sold(self):
return self.get_queryset().annotate(copies=Sum('book__copies_sold')
class Author(models.Model):
first_name = models.CharField(max_length=120)
last_name = models.CharField(max_length=120)
objects = AuthorManager()
class Book(models.Model):
title = models.CharField(max_length=120)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
[已编辑]
谢谢 schillingt 的回复。我补充说:
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
return self.annotate(copies=Sum('books__copies_sold'))
我试过类似的东西:
author_books = Author.objects.filter(id=2).total_copies_sold()
>>> author_books.copies
我得到了
'AuthorQueryset' object has no attribute 'copies'
您需要使用Manager.from_queryset
来设置您的管理员。这是 docs.
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
...
class Author(models.Model):
objects = models.Manager.from_queryset(AuthorQueryset)()
您正在寻找的是:
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('books__copies_sold'))
class Author(models.Model):
objects = AuthorManager()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
现在可以链接查询,例如:
author_total_books = Author.objects.total_copies_sold().first()
但是您将无法在 QuerySet 对象上使用它,例如:
author_books = Author.objects.filter(id=2).total_copies_sold()
那是因为您注释的是 Author 对象,而不是 QuerySet。要获得该结果,您应该执行:
Author.objects.annotate_with_copies_sold().get(id=2)
author.copies_sold
15
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
# Write your solution here
return self.annotate(copies_sold=Coalesce(Sum('books__copies_sold'), 0))
class Author(models.Model):
# Make sure this manager is available.
objects = AuthorManager()
# objects = models.Manager.from_queryset(AuthorQuerySet)()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
enter code here
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('Book_Author__copies_sold'))
class Author(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
objects = AuthorManager()
class Meta:
verbose_name_plural = "Author"
verbose_name = 'Author'
ordering = ('first_name','last_name')
class Book(models.Model):
title = models.CharField(max_length=250, unique=True)
copies_sold = models.PositiveIntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='Book_Author')
class Meta:
verbose_name_plural = "Book"
verbose_name = 'Book'
ordering = ('title','copies_sold')
from vehicles.models import Author, Book
try:
author = Author.objects.get(first_name='Mark', last_name='Twain')
except Author.DoesNotExist:
author = Author.objects.create(first_name='Mark', last_name='Twain')
try:
book = Book.objects.get(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
pass
try:
book = Book.objects.get(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
pass
author = Author.objects.annotate_with_copies_sold().first()
print(author.copies_sold)
11
1.Create AuthorManager, AuthorQuerySet classes from Author and Books
2.Create Author, Book models
3.Prepare Test Data and use model manager to filter the queryset