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 - 弦圈
更多其他趣味内容: 弦圈 - 找到属于你的圈子

相关推荐
淼澄研学1 分钟前
PyTorch深度学习实战:5个核心方法从0到1构建神经网络
前端·数据库·python
吴声子夜歌9 分钟前
MongoDB 4.2——分片简介
数据库·mongodb
腾渊信息科技公司16 分钟前
工业时序数据存储选型实战:从PostgreSQL到TDengine,查询从15秒到200ms
数据库·postgresql·tdengine
TDengine (老段)28 分钟前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine
米码收割机30 分钟前
【Python】Python Django+Vue3校园自习室预约管理系统(源码+文档+PPT)【独一无二】
开发语言·python·django
l1t41 分钟前
PostgreSQL 11–18 中的 SQL 改进:个人精选-1
数据库·sql·postgresql
逃跑的浣熊1 小时前
MySQL 性能分析报告:Page Cache 与 fsync 对读写性能的影响
数据库
路由侠内网穿透.1 小时前
本地部署开源日志收集系统 Log Bull 并实现外部访问
运维·服务器·网络·数据库·开源
码云数智-大飞2 小时前
PHP 大文件上传、断点续传完整实现思路
数据库
sevenll072 小时前
SqlKit - 覆盖 50+ 数据库的 AI 智能体 SQL 桌面客户端
数据库·人工智能·sql·智能体