Django Model validate_unique方法不会引发ValidationError

时间:2016-03-10 22:18:34

标签: django django-models django-admin raise validationerror

我的模特是:

class Inventory(models.Model):
    canteen_id = models.IntegerField()
    item = models.OneToOneField('Info',db_column='item_id')

我希望每个canteen_id的项目都应该是唯一的。我使用unique_together,但它不能作为项目在OneToOneField中使用。 我正在为我的模型使用validate_unique方法,现在我的代码是:

class Inventory(models.Model):
    canteen_id = models.IntegerField()
    item = models.OneToOneField('Info',db_column='item_id')
    unit_price = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=1)
    sales_vat = models.DecimalField(decimal_places=2,max_digits=5,default=0.0)
    date_time = models.DateField(auto_now=False,auto_now_add=True)

def vat_count(self):
    self.item_price = Decimal(self.unit_price)
    self.vat = (self.item_price * 15)/100
    return self.vat

def validate_unique(self, exclude=None):
    qs = Inventory.objects.filter(canteen_id=self.canteen_id)
    if self.pk is None:
        if qs.filter(item=self.item).exists():
            raise ValidationError("item already exists")


def save(self, *args,**kwargs):
    self.canteen_id = CANTEEN_ID
    self.sales_vat = self.vat_count()
    self.unit_price = Decimal(self.unit_price) 
    self.validate_unique()
    super(Inventory,self).save(*args, **kwargs) 

现在,当我尝试添加相同的项目和canteen_id时,它不会在表单页面中引发任何错误消息。它显示错误。错误:

Environment:   
Request Method: POST
Request URL: http://localhost:8000/admin/item/inventory/add/

Django Version: 1.9.2
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'item',
 'bill',
 'system']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
  541.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
  244.             return view(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
  1437.         return self.changeform_view(request, None, form_url, extra_context)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in inner
  184.                     return func(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in changeform_view
  1378.                 self.save_model(request, new_object, form, not add)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_model
  991.         obj.save()

File "/home/harun/Desktop/nutboltu/canteenLatest/CanteenKiosk/diucanteen/item/models.py" in save
  34.         self.validate_unique()

File "/home/harun/Desktop/nutboltu/canteenLatest/CanteenKiosk/diucanteen/item/models.py" in validate_unique
  27.                 raise ValidationError("item already exists")

Exception Type: ValidationError at /admin/item/inventory/add/
Exception Value: [u'item already exists']

解决方案是什么?

4 个答案:

答案 0 :(得分:3)

谢谢大家帮我找出问题所在。我的代码是正确的,但我在查询中犯了一个错误。我通过在settings.py中分配变量CANTEEN_ID来获取canteen_id值,并通过save()方法保存它。 所以,我的查询应该是:

from projectdir.settings import CANTEEN_ID
def validate_unique(self,exclude=None):    
    qs = Inventory.objects.filter(canteen_id=CANTEEN_ID)

答案 1 :(得分:2)

如果您在模型中覆盖validate_unique方法,则应像保存/删除等一样调用super

def validate_unique(self, exclude=None):
    # custom logic
    super(Inventory, self).validate_unique(exclude=exclude)

答案 2 :(得分:1)

首先,我认为unique_together应该与一对一的字段一起使用。如果你可以创建一个简单的测试用例来表明它没有,那么就值得创建一个错误报告。

如果您确实想手动检查唯一约束,请不要在save()方法中执行此操作。 Django管理员不期望在save方法中引发验证错误,因此您会收到错误。相反,覆盖模型的clean方法,并进行检入。模型表单(包括Django管理员中的表单)将在处理表单数据时调用clean方法。

class Inventory(models.Model):
    ...
    def clean(self):
        qs = Inventory.objects.filter(canteen_id=self.canteen_id)
        if self.pk is None:
            if qs.filter(item=self.item).exists():
            raise ValidationError("item already exists")

有关详细信息,请参阅validating objects上的文档。

答案 3 :(得分:0)

为save方法提供CANTEEN_ID的方式可能隐藏解决方案。