Django CharField To String

I am creating a tag system in Django and want to allow spaces and other characters in the tag name to display, but filter them and use lowercase letters when matching names, etc.

To this end, I added a field to my tag model like this:

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

However, I ran into a problem, CharField is not a string, and for my life I cannot learn how to convert it to one!

+3
source share
3 answers

You define classthere, therefore nameit is not a string, but a Django Field .

In addition, converting nameto matchnameat the class level makes no sense. You must do this on an instance.

, :

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

CharField, .

class Tag(models.Model):
    name = models.CharField(max_length=200, unique=True)
    matchname = models.CharField(max_length=200, unique=True)

, :

class Tag(models.Model):

    def save(self):
        self.matchname = re.sub("\W+" , "", self.name.lower())
        super(Tag,self).save()

:

from django.db.models.signals import pre_save

def populate_matchname(sender,instance,**kwargs):
    instance.matchname = re.sub("\W+" , "", instance.name.lower())

pre_save(populate_matchname,sender=Tag)
+4

You can add a method:

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

And use the decorator property:

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

All this will allow you to access the tag namewith lower case and without characters without words. But you will not get it in the DB. If you want this, you need to add another CharFieldand save nameand matchname.

+2
source

Source: https://habr.com/ru/post/1723659/


All Articles