[英]Save django charfield with spaces replaced on model save
I'm trying to save a CharField
to another CharField
on model save in django. 我试图将一个CharField
保存到Django保存的模型上的另一个CharField
中。 I've done the following: 我已经完成以下工作:
class Mall(models.Model):
name = models.CharField(max_length=200)
raw_name = models.CharField(editable=False, max_length=300) #to prevent from appearing in admin
def save(self):
if not self.id:
self.raw_name = self.name.replace(" ", "_")
super(Mall, self).save()
However, this isn't working and it saves as an empty string. 但是,这不起作用,并且另存为空字符串。 What am I doing wrong? 我究竟做错了什么?
According to the "Overriding predefined model methods" paragraph: 根据“覆盖预定义的模型方法”段落:
It's also important that you pass through the arguments that can be passed to the model method – that's what the *args, **kwargs bit does. 传递可传递给模型方法的参数也很重要-这就是* args,** kwargs位的作用。 Django will, from time to time, extend the capabilities of built-in model methods, adding new arguments. Django会不时扩展内置模型方法的功能,并添加新的参数。 If you use *args, **kwargs in your method definitions, you are guaranteed that your code will automatically support those arguments when they are added. 如果在方法定义中使用* args和** kwargs,则可以确保代码添加后将自动支持这些参数。
In other words, you need to pass *args
and **kwargs
along: 换句话说,您需要传递*args
和**kwargs
:
def save(self, *args, **kwargs):
if not self.id:
self.raw_name = self.name.replace(" ", "_")
super(Mall, self).save(*args, **kwargs)
You can make the raw_name be a SlugField. 您可以将raw_name设为SlugField。 Especially useful with prepopulated fields 对预填充的字段特别有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.