为什么Django中的Model.save()函数不会被覆盖? [英] Why won't this override of the Model.save() function in Django work?

查看:478
本文介绍了为什么Django中的Model.save()函数不会被覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的通用博客应用程序中,基于 http://www.djangoproject.com/ ,我试图通过使用slugify将它们保存到数据库中来创建帖子()方法对帖子的标题。这里是posts.models.py:

  from django.db import models 
from django.template.defaultfilters import slugify
import datetime

class Post(models.Model):

def __unicode __(self):
return self.title

title = models.CharField(max_length = 200)
slug = models.SlugField(editable = False)
body = models.TextField()
pub_date = models.DateTimeField('date published ')

def save(self,* args,** kwargs):
if not self.id:
self.slug = slugify(self.title)
super(Post,self).save(* args,** kwargs)

不幸的是,尝试启动服务器时出现以下例外:

 文件/ Users / modocache / Programming / Django / blog / posts / models .py,第24行,Post 
super(Post,self).save(* args,** kwargs)
NameError:name'Post'未定义

我很困惑,为什么会引发NameError?我以为我正在使用super()方法错误,但是这样做虽然似乎和上面尝试的一样:

  class Foo(object):
def say_spam(self):
printSpam!

class Bar(Foo):
def say_spam(self):
print由...带来:
super(Bar,self).say_spam()
打印鸡蛋!

b = Bar()
b.say_spam()

所以如果这样做,为什么上面的Django片段不会失败?这很令人困惑,考虑到djangoproject.com的文档说这应该是有效的:

 #http://docs.djangoproject.com/en / dev / topics / db / models /#overriding-model-methods 

class Blog(models.Model):
name = models.CharField(max_length = 100)
标语= models.TextField()

def save(self,* args,** kwargs):
do_something()
super(Blog,self).save(* args, ** kwargs)#调用realsave()方法。
do_something_else()

感谢任何和所有的帮助提前,我真的很感激it!

解决方案

modocache,



你是什么版本的django使用?你在那里列出的应该工作,我在许多我自己的模型中使用相同的逻辑,它的工作正常。



根据此页面: http://fosshelp.blogspot.com/2010/12/django-override-save-method-two-ways.html



你应该可以改变代码看起来像这样(下面),它会做同样的事情,但不会引用Post模型。



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $¬
models.Model.save(self,* args,** kwargs)#< - 注意自己


$ b另一点,而不是使用if not self.id,而是更好的做法是使用if not self.pk:。看这些相关链接。



Django queries - id vs pk



http://docs.djangoproject.com/en/dev/ref/models/instances/#the-pk-property



如何帮助。


I am new to SO and Python/Django, so please bear with me.

In my generic blog app based on the tutorial at http://www.djangoproject.com/, I am trying to create slugs for posts when they are saved to the database by using the slugify() method on the post's title. Here is posts.models.py:

from django.db import models
from django.template.defaultfilters import slugify
import datetime

class Post( models.Model ):

    def __unicode__(self):
        return self.title

    title = models.CharField( max_length = 200 )
    slug  = models.SlugField( editable = False )
    body = models.TextField()
    pub_date = models.DateTimeField('date published')

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify( self.title )
        super( Post, self ).save( *args, **kwargs )

Unfortunately, this throws the following exception upon attempting to start the server:

File "/Users/modocache/Programming/Django/blog/posts/models.py", line 24, in Post
super( Post, self ).save( *args, **kwargs )
NameError: name 'Post' is not defined

I am confused as to why NameError is thrown. I thought I was using the super() method wrong, but this works, despite it seeming like the same thing I'm attempting above:

class Foo( object ):
    def say_spam( self ):
        print "Spam!"

class Bar( Foo ):
    def say_spam( self ):
        print "Brought to you by:"
        super( Bar, self ).say_spam()
        print "Eggs!"

b = Bar()
b.say_spam()

So if this works, why doesn't the above Django snippet fail? This is especially puzzling considering djangoproject.com's documentation says this should work:

# http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        do_something()
        super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
        do_something_else()

Thanks for any and all help in advance, I'd really appreciate it!

解决方案

modocache,

What version of django are you using? What you have there listed should work, I use that same logic in many of my own models, and it works fine.

According to this page: http://fosshelp.blogspot.com/2010/12/django-override-save-method-two-ways.html

you should be able to change the code to look like this (below), and it will do the same thing but won't reference the Post model.

 def save(self, *args, **kwargs):
    if not self.id:
        self.slug = slugify( self.title )
    models.Model.save(self, *args, **kwargs ) # <-- notice the self

Another point , instead of using "if not self.id:" it is generally better practice to use "if not self.pk:" instead. see these related links.

Django queries - id vs pk

http://docs.djangoproject.com/en/dev/ref/models/instances/#the-pk-property

How that helps.

这篇关于为什么Django中的Model.save()函数不会被覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆