我正在尝试覆盖模型上的save方法,以确保新实例正确填充了多对多字段。我在重写方法中做的第一件事是调用super()save方法。但不知何故,这导致了完整性错误。有什么想法吗?
File: models.py
class Bill(models.Model):
''' A shared bill '''
total_cost = models.DecimalField(max_digits=8, decimal_places=2)
description = models.CharField(max_length=80)
fronting_user = models.ForeignKey(BillsUser,
on_delete=models.PROTECT,
related_name='fronted_bill_set')
splitting_users = models.ManyToManyField(BillsUser,
related_name='split_bill_set',
through='BillShare',
through_fields=('bill', 'owed_by'))
group = models.ForeignKey(BillsGroup)
def save(self, *args, **kwargs):
if not self.pk:
is_new_instance = True
super(Bill, self).save(self, *args, **kwargs)
if is_new_instance:
members = self.group.users.all()
for bu in members:
amount = (payer_share_amt(total_cost, len(members))
if bu == self.fronting_user
else share_amt(total_cost, len(members)))
BillShare.objects.create(owed_by=bu,
owed_to=self.fronting_user,
total_amount=amount,
amount_unpaid=amount)
尝试在管理视图中保存未更改的实例时返回跟踪:
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/bills/bill/3/change/
Django Version: 1.9.2
Python Version: 3.5.1
Installed Applications:
['bills',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/usr/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute
323. return Database.Cursor.execute(self, query, params)
The above exception (UNIQUE constraint failed: bills_bill.id) was the direct cause of the following exception:
File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper
541. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/contrib/admin/options.py" in change_view
1440. return self.changeform_view(request, object_id, form_url, extra_context)
File "/usr/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/lib/python3.5/contextlib.py" in inner
30. return func(*args, **kwds)
File "/usr/lib/python3.5/site-packages/django/contrib/admin/options.py" in changeform_view
1378. self.save_model(request, new_object, form, not add)
File "/usr/lib/python3.5/site-packages/django/contrib/admin/options.py" in save_model
991. obj.save()
File "/media/sf_Dropbox/python/projects/phoenixbills/phoenixbills/bills/models.py" in save
57. super(Bill, self).save(self, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/db/models/base.py" in save
700. force_update=force_update, update_fields=update_fields)
File "/usr/lib/python3.5/site-packages/django/db/models/base.py" in save_base
728. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/lib/python3.5/site-packages/django/db/models/base.py" in _save_table
812. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert
851. using=using, raw=raw)
File "/usr/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/db/models/query.py" in _insert
1039. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
1060. cursor.execute(sql, params)
File "/usr/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/usr/lib/python3.5/site-packages/django/db/utils.py" in __exit__
95. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/lib/python3.5/site-packages/django/utils/six.py" in reraise
685. raise value.with_traceback(tb)
File "/usr/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/usr/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute
323. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /admin/bills/bill/3/change/
Exception Value: UNIQUE constraint failed: bills_bill.id