Populating django field with pre_save()?

前端 未结 5 1188
囚心锁ツ
囚心锁ツ 2020-12-13 05:39
class TodoList(models.Model):
    title = models.CharField(maxlength=100)
    slug = models.SlugField(maxlength=100)
    def save(self):
        self.slug = title
           


        
5条回答
  •  生来不讨喜
    2020-12-13 06:22

    Most likely you are referring to django's pre_save signal. You could setup something like this:

    from django.db.models.signals import pre_save
    from django.dispatch import receiver
    from django.template.defaultfilters import slugify
    
    @receiver(pre_save)
    def my_callback(sender, instance, *args, **kwargs):
        instance.slug = slugify(instance.title)
    

    If you dont include the sender argument in the decorator, like @receiver(pre_save, sender=MyModel), the callback will be called for all models.

    You can put the code in any file that is parsed during the execution of your app, models.py is a good place for that.

提交回复
热议问题