Home > OS >  How to make it so that when saving data in the database, the data generated by the function is autom
How to make it so that when saving data in the database, the data generated by the function is autom

Time:09-30

I'm writing a site on Django and ran into a problem

I have a title field in the database, which stores the title of the book, but I want to add a chunk_title field, which will store the title of the book, divided into chunks of 3 characters, I wrote a method that does this, but I need that when inserted into the database, it was automatically applied and its result was inserted into chunk_title

This is my DB model,where the last field is the field I want to auto-generate the value into:

class Book(models.Model):
    """
    Клас,який зберігає всі книги на сайті
    """

    title = models.CharField(max_length=120, default=' ', verbose_name='Назва')
    description = models.TextField(verbose_name='Опис')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категорія')
    date_at = models.DateField(auto_now_add=True, verbose_name='Дата створення')
    image = models.ImageField(upload_to='photos/%Y/%m/%d/')
    authors = models.ManyToManyField(Author, verbose_name='Автори')
    content = models.FileField(upload_to='contents/%Y/%m/%d/', blank=True)
    price = models.IntegerField(verbose_name='Ціна', default='0')
    chunk_title_book = models.TextField(default=' ')

And this is my method, the result of which I want to insert into that field (it is in the same class, i.e. Book):

    def chunk_title(self, string: str) -> str:
        """
        Розбиває назву книги на чанки по 3 символи макисмум для подальшого пошуку по цих чанках
        """
        chunk_string = ' '.join(textwrap.wrap(string, 3))
        return chunk_string   ' '   ' '.join(string.split())

Does anyone know if this is possible to implement, and if yes, how?

CodePudding user response:

You need to overwrite the save method of django Model, and assign the value of chunk_title_book by calling the function:

class Book(models.Model):
    """
    Клас,який зберігає всі книги на сайті
    """
    .
    .
    .
    .
    def save(self, *args, **kwargs):
        # overwriting `chunk_title_book` attribute 
        # Assumes chunk_title function is Book class's method
        self.chunk_title_book = self.chunk_title(self.title)
        super(Book, self).save(*args, **kwargs)
  • Related