python - 属性错误: 'tuple' object has no attribute 'client'

标签 python django django-models django-rest-framework

我尝试从模型访问cached_property及其返回 “tuple”对象没有属性“client”

这是具有cached_property的模型

class Creds(models.Model):
    tenant = models.OneToOneField('tenant.Tenant', unique=True, on_delete=models.CASCADE)


    @cached_property
    def client(self):
        from pos.api_client import APIClient
        return APIClient(self)

这是我尝试访问cached_property的地方。并得到错误。

class createCred(APIView):
    def get(self, request, *args, **kwargs):

        tenant = get_object_or_404(Tenant, pk=request['tenant_id'])
        square_credential = SquareCredential.objects.get_or_create(tenant=tenant)
        client = square_credential.client

最佳答案

检查文档中的 get_or_create

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

所以你需要类似的东西:

square_credential, created = SquareCredential.objects.get_or_create(tenant=tenant)
client = square_credential.client

如果您不关心它是否被创建,您可以使用下划线作为“一次性变量”约定:

square_credential, _ = SquareCredential.objects.get_or_create(tenant=tenant)

关于python - 属性错误: 'tuple' object has no attribute 'client' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55266018/

相关文章:

python - 用于匹配特定 URL 的正则表达式

python - Mac 10.6.8 上的 postgres 安装错误

python - Django 查询按字符串值排序

python - Django 获得大量 SuspiciousOperation : Invalid HTTP_HOST header

python - Django/Python 更新字段值(在模型保存期间)

具有来自另一个模型的默认值的 Django 模型字段

python - 包含 2 个元素和一个 zip 的循环

python - 如何在 LibreOffice Calc 中使用 PyUNO 更改单元格边框的线宽?

python - pysftp 和 paramiko 在几秒钟后停止上传文件

python - 我如何将 DecimalField 转换为在 Python Django 中 float ?