gpt4 book ai didi

python - 带有注释的 Django 查询集

转载 作者:行者123 更新时间:2023-12-01 21:48:21 25 4
gpt4 key购买 nike

我正在 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'

最佳答案

你正在寻找的是:

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

关于python - 带有注释的 Django 查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59954022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com