Django异常DoesNotExist
我有一个模型同时具有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”,即使“Vars”属性不是django模型的一部分,django也会不断提升DoesNotExist异常。
任何人都可以解释为什么会发生?
编辑:按要求:
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)
请求48中的文件“/home/gleal/cbengine/engine/wsgi/openshift/views.py”。return browse(request,app,model,var_dict,False)
文件“/home/gleal/cbengine/engine/wsgi/openshift/../openshift/subviews/browse.py”in _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“in get 343. raise self.field.rel.to.DoesNotExist
异常类型:DoesNotExist at / estoque / estoque / browse / Exception Value:
刚才发现那个伟大的恶棍是方法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}
感谢任何试图帮助的人!
链接地址: http://www.djcxy.com/p/55907.html