我在我的django ModelAdmin類中有一個overritten save_model()
方法。該型號有ManyToMany
字段。 我save_model
看起來是這樣的:django model.delete()引發ValueError - 在可以使用此多對多關係之前需要有一個字段值
def save_model(self, request, obj, form, change):
creating = False
to_delete = False
if not obj.pk:
creating = True
obj.save()
form.save_m2m()
# DETECT SOMETHING (some complicated conditions) HERE ...
detected =True
if detected:
obj.delete() # --> here is my problem
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in wrapper
366. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/Library/Python/2.7/site-packages/django/db/transaction.py" in inner
209. return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in add_view
956. self.save_related(request, form, formsets, False)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in save_related
731. form.save_m2m()
File "/Library/Python/2.7/site-packages/django/forms/models.py" in save_m2m
83. f.save_form_data(instance, cleaned_data[f.name])
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in save_form_data
1273. setattr(instance, self.attname, data)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in __set__
859. manager = self.__get__(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in __get__
846. through=self.field.rel.through,
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py" in __init__
538. (instance, source_field_name))
Exception Type: ValueError at /admin/lawis_core/invoice/add/
Exception Value: "<Invoice: 1301000>" needs to have a value for field "invoice" before this many-to-many relationship can be used.
加入追蹤 - 感謝 – kosta5 2013-02-08 17:04:42