django对象报错object has no attribute ‘count‘

提问

我正在学习django/python,并被一个问题给卡住了。

我有一个视图:create_document.py,我想在其中计算模型类NameDetails中的名字细节数量。

但我不知道正确的写法!

这是我models.py的代码:

python 复制代码
class NameDetails(FillableModelWithLanguageVersion):
    user = models.ForeignKey(User)
    name_details_prefix_title = models.CharField(null=True, blank=True, max_length=25)
    name_details_first_name = models.CharField(null=False, blank=False, max_length=50)
    name_details_middle_name = models.CharField(null=True, blank=True, max_length=100)
    ....

这是我create_document.py的代码,里面用到了django wizard。我想要确定的是用户在他们能够创建文档前,至少有一个名字。

python 复制代码
from app_name.core.models import NameDetails

class CreateDocumentWizard(SessionWizardView):
    template_name = 'documents/document_create.html'

    form_list = [
        core_forms.CreateDocumentWizardForm01,
        core_forms.CreateDocumentWizardForm02,
        core_forms.CreateDocumentWizardForm03,
        core_forms.CreateDocumentWizardForm04,
    ]

    def get_form_kwargs(self, step=None):
        kwargs = super(CreateDocumentWizard, self).get_form_kwargs(step)
        kwargs.setdefault('user', self.request.user)
        return kwargs

    def get_context_data(self, form, **kwargs):

        name_details_count = NameDetails(user=self.request.user).count()
        if name_details_count < 1:
            return redirect(settings.MENU_DETAIL_LINK_NAME_DETAILS)

当我使用name_details_count = NameDetails(user=self.request.user).count()确定用户的NameDetails计数时,我得到了以下错误:

NameDetails' object has no attribute 'count'

我已经尝试了很多种组合,但现在还是卡住了。

回答1

你的get_context_data函数应该这样写:

python 复制代码
name_details_count = NameDetails.objects.filter(user=self.request.user).count()

回答2

眼下你正在以request.user为用户创建一个全新的NameDetails实例。相反,你应该查询数据库中当前用户已有的NameDetails,并对他们进行计数。你可以通过NameDetails.objects查询数据库:

python 复制代码
name_details_count = NameDetails.objects.filter(user=self.request.user).count()

欢迎来弦圈一起翻译StackOverflow等国外编程内容👇👇👇
翻译原文: django对象报错object has no attribute 'count'
更多Django相关内容: Django - 弦圈
更多其他趣味内容: 弦圈 - 找到属于你的圈子

相关推荐
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
c8i2 天前
django中的FBV 和 CBV
python·django
DemonAvenger2 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥2 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud2 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug3 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom3 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试