4

我的模型是:

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

4 回答 4

4

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

def validate_unique(self, exclude=None):
    # custom logic
    super(Inventory, self).validate_unique(exclude=exclude)
于 2016-03-11T01:57:02.327 回答
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)
于 2016-03-14T08:44:27.097 回答
2

首先,我认为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")

有关更多信息,请参阅有关验证对象的文档。

于 2016-03-11T13:58:28.053 回答
0

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

于 2016-03-11T13:47:21.173 回答