Django CharField转换为字符串 [英] Django CharField To String

查看:57
本文介绍了Django CharField转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django中构建标记系统,并希望在标记名称中允许显示空格和其他字符,但要过滤掉它们并在匹配名称等时使用小写字母.

I'm building a tagging system in Django and would like to allow spaces and other characters in the tag name for display but filter them out and use lower case when matching names etc.

为此,我已经在Tag模型中添加了一个字段,如下所示:

To that end I have added a field to my Tag model as so:

class Tag(models.Model):
    name = models.CharField(max_length=200, unique=True)
    matchname = re.sub("\W+" , "", name.lower())

但是我遇到了一个问题,CharField不是字符串,我一生都无法找到如何将其转换为字符串的方法!

However I am running into a problem, the CharField is not a string and I cannot for the life of me find out how to convert it to one!

推荐答案

您正在此处定义 class ,因此 name 不是字符串,而是 Django字段.

You're defining a class there so name is not a string it's a Django Field.

此外,在类级别将 name 转换为 matchname 没有任何意义.您应该在实例上执行此操作.

Additionally, converting name to matchname at the class level doesn't make any sense. You should be doing this on the instance.

您可以在类中添加一个方法来做到这一点:

You could add a method to your class to do this:

def get_matchname(self):
    """Returns the match name for a tag"""
    return re.sub("\W+" , "", self.name.lower())

这篇关于Django CharField转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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