我试图覆盖我的模型的方法save()
:
class Article(models.Model):
number = models.PositiveIntegerField(editable=False)
def save(self, *args, **kwargs):
if not self.pk: #means: if objects wasn't saved before
self.number = Article.objects.count() +1 #number is 1-based
super(Article, self).save(*args, **kwargs)
现在我尝试从管理页面添加新文章。我得到的错误:
self.number = Article.objects.count() +1
NameError: name 'self' is not defined
我做错了什么?
number
是某种ID
,以我的方式订购对象,但这些ID
不应手动更改number
不允许为空或空白,因此我必须在第一次保存之前设置一个值(这是我尝试使用该代码段的内容)number
应等于所有对象的数量(保存后),基于1的计数追踪(最近一次呼叫最后一次):
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 544, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/sites.py", line 211, in inner
return view(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1509, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/lib/python3.5/contextlib.py", line 30, in inner
return func(*args, **kwds)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1449, in changeform_view
self.save_model(request, new_object, form, not add)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1007, in save_model
obj.save()
File "/media/[directory to my projects]/projects_actual/myproject/myapp/models.py", line 69, in save
seĺf.number = Article.objects.count() + 1
NameError: name 'seĺf' is not defined
[16/Apr/2017 11:07:00] "POST /admin/myapp/article/add/ HTTP/1.1" 500 121043
你错过了一些信息吗?