Filip Simin
Filip Simin

Reputation: 578

Clone model object values Django

i want to clone the values from existing model object and sanitize the values for special characters to provide a better search. So i already have values in the database that i want to sanitize and store in a new object after.

This is a code example:

class Entry(models.Model):
    headline = models.CharField(max_length=255)
    sanitized_headline = models.CharField(max_length=255)

I would like populate all the sanitized_headline objects with the corresponding headline values after some character replacements like this re.sub('č', 'c', headline) applied to headline before cloning, as well as do this for every new entry.

Im using Django for a GraphQl API character replacement can't be done through a view.

Thank you

Upvotes: 1

Views: 133

Answers (1)

Amir Afianian
Amir Afianian

Reputation: 2797

To sanitize the existing objects: [provided that you have a function to sanitize the text called sanitize]

Enter your Django shell (using python manage.py shell) and import Entry model. Then:

all_entries = Entry.objects.all()
for obj in all_entries:
    obj.sanitized_headline = sanitize(obj.headline)
    obj.save()

To automatically sanitize new objects, you have to override the save method:

class Entry(models.Model):
    headline = models.CharField(max_length=255)
    sanitized_headline = models.CharField(max_length=255)

    def save(self, *args, **kwargs):
        self.sanitized_headline = sanitize(self.headline)
        super().save(*args, **kwargs)

Upvotes: 3

Related Questions