I want to input something like(via the admin page):
text = 't(es)t'
and save them as:
'test'
on database.
And I use this Regex to modify them:
re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', text)
I know how to transform text from 't(es)t'
to 'test'
but the problem is
when i use
name = models.CharField(primary_key=True, max_length=16)
to input text(from admin). It immediately save to database cannot modify it before saving.
Finally, From a single input from admin text = 't(es)t'
(CharField).
What do i want?
't(es)t'
as a string variable.'test'
to databaseTo save changes to an object that's already in the database, use save() . This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .
save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database. update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.
When you overwrite a function (of a class) you can call the function of the parent class using super . The save function in the models records the instance in the database. The first super(Review, self). save() is to obtain an id since it is generated automatically when an instance is saved in the database.
Try to overide the save method in your model,
class Model(model.Model):
name = models.CharField(primary_key=True, max_length=16)
# This should touch before saving
def save(self, *args, **kwargs):
self.name = re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', self.name)
super(Model, self).save(*args, **kwargs)
Update:
class Model(model.Model):
name = models.CharField(primary_key=True, max_length=16)
name_org = models.CharField(max_length=16)
# This should touch before saving
def save(self, *args, **kwargs):
self.name = re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', self.name)
self.name_org = self.name # original "t(es)t"
super(Model, self).save(*args, **kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With