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

相关推荐
清水白石00813 分钟前
解构异步编程的两种哲学:从 asyncio 到 Trio,理解 Nursery 的魔力
运维·服务器·数据库·python
资生算法程序员_畅想家_剑魔15 分钟前
Mysql常见报错解决分享-01-Invalid escape character in string.
数据库·mysql
PyHaVolask41 分钟前
SQL注入漏洞原理
数据库·sql
ptc学习者1 小时前
黑格尔时代后崩解的辩证法
数据库
代码游侠1 小时前
应用——智能配电箱监控系统
linux·服务器·数据库·笔记·算法·sqlite
!chen1 小时前
EF Core自定义映射PostgreSQL原生函数
数据库·postgresql
霖霖总总1 小时前
[小技巧14]MySQL 8.0 系统变量设置全解析:SET GLOBAL、SET PERSIST 与 SET PERSIST_ONLY 的区别与应用
数据库·mysql
马克学长1 小时前
SSM校园食堂订餐系统531p9(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架·ssm 校园食堂订餐系统
alonewolf_991 小时前
深入剖析MySQL索引底层:B+树、联合索引与跳跃扫描原理全解
数据库·b树·mysql
oMcLin2 小时前
如何在 AlmaLinux 9 上配置并优化 Redis 集群,支持高并发的实时数据缓存与快速查询?
数据库·redis·缓存