保存Django charfield,替换模型s上的空格

2024-05-06 11:46:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在django中的model save中将CharField保存到另一个CharField。我已经完成了以下工作:

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()

但是,这不起作用,它保存为空字符串。我做错什么了?在


Tags: djangonameselfrawmodelmodelssavelength
2条回答

根据"Overriding predefined model methods"段:

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. Django will, from time to time, extend the capabilities of built-in model methods, adding new arguments. 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和{}:

def save(self, *args, **kwargs):
    if not self.id:
        self.raw_name = self.name.replace(" ", "_")
    super(Mall, self).save(*args, **kwargs)

你可以把原始名字变成SlugField。对prepopulated fields特别有用

相关问题 更多 >