Django异常DoesNotExist

1 投票
1 回答
1059 浏览
提问于 2025-04-18 07:42

我有一个模型,它同时包含了Django的模型字段和Python的属性。例如:

编辑2:更新了实际的模型(抱歉,名字是葡萄牙语)

#On Produto.models.py
from django.db          import models
from django.forms       import ModelForm
from openshift.models   import AbstractModel

from openshift.produto.models import app_name


class Produto(models.Model):

    class Meta:
        app_label = app_name


    descricao = models.CharField(max_length=128)    
    und_choices = (
        ('UND', 'Unidade'),
        ('M',     'Metro'),
        ('Kg',     'Quilograma'),
        ('PC',     'Peça'),
    )
    unidade   = models.CharField(max_length=3, choices=und_choices, default='UND')

#On Estoque.models.py

from django.db          import models
from django.forms       import ModelForm
from openshift.models   import AbstractModel
from produto.models     import Produto

from openshift.estoque.models import app_name

class Estoque(models.Model):

    class Meta:
        app_label = app_name

    id = models.IntegerField(primary_key=True)
    produtoid   = models.ForeignKey(Produto, unique=True)
    quantidade  = models.DecimalField(max_digits=20, decimal_places=4)
    valorunit   = models.DecimalField(max_digits=20, decimal_places=4)
    valortotal  = models.DecimalField(max_digits=20, decimal_places=2)   


    _field_labels = {
        "id" : r"Código", 
        "produtoid"  : r"Produto", 
        "quantidade" : r"Quantidade",
        "valorunit" : r"Valor Unitário",
        "valortotal" : r"Valor Total"
    }

    _view_order = ['id', 'produtoid', 'quantidade', 'valorunit', 'valortotal']

    @property
    def Vars(self):
        return {'field_labels': self._field_labels, 'view_order': self._view_order}

#on project.views.main_request

obj = get_model('Estoque', 'Estoque')().Vars #Here is where the Exception triggers.

如果我在调用save()方法之前尝试访问“Vars”这个属性(也就是在创建模型记录的时候),Django会一直抛出一个DoesNotExist的异常,尽管“Vars”这个属性并不是Django模型的一部分。

有没有人能解释一下为什么会发生这种情况?

编辑:应要求:

Django的追踪信息:

追踪信息:

文件 "/home/gleal/cbengine/local/lib/python2.7/site-packages/django/core/handlers/base.py" 在get_response中 111. response = callback(request, *callback_args, **callback_kwargs)

文件 "/home/gleal/cbengine/engine/wsgi/openshift/views.py" 在req中 48. return browse(request, app, model, var_dict, False)

文件 "/home/gleal/cbengine/engine/wsgi/openshift/../openshift/subviews/browse.py" 在_browse中 32. custom_vars['TableColspan'] = len(obj.Vars.get('VIEW_ORDER', {}))

文件 "/home/gleal/cbengine/engine/wsgi/openshift/../openshift/models.py" 在 Vars中 40. curr_vals[field.name] = getattr(self, field.name) 文件 "/home/gleal/cbengine/local/lib/python2.7/site-packages/django/db/models/fields/related.py" 在get中 343. raise self.field.rel.to.DoesNotExist

异常类型:DoesNotExist 在 /estoque/estoque/browse/ 异常 值:

1 个回答

0

我刚刚发现,问题的关键在于方法 Vars 上的 @property 装饰器。

这个装饰器让 Django 尝试从类的实例中获取值,有时候这会触发 Django 的 ORM 去数据库查询(简单来说,就是在我试图从当前实例获取值时)。

我把 @property 改成了 @classmethod,结果一切都正常了。像这样:

#before
@property
def Vars(self):
    return {'field_labels': self._field_labels, 'view_order': self._view_order}

#after
@classmethod
def Vars(self):
    return {'field_labels': self._field_labels, 'view_order': self._view_order}

感谢所有尝试帮助我的人!

撰写回答