使用 pre_save() 填充 Django 字段? [英] Populating django field with pre_save()?

查看:50
本文介绍了使用 pre_save() 填充 Django 字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class TodoList(models.Model):
    title = models.CharField(maxlength=100)
    slug = models.SlugField(maxlength=100)
    def save(self):
        self.slug = title
        super(TodoList, self).save()

我假设以上是在表TodoList中插入标题时如何创建和存储slug,如果不是,请纠正我!

I'm assuming the above is how to create and store a slug when a title is inserted into the table TodoList, if not, please correct me!

无论如何,我一直在研究 pre_save() 作为执行此操作的另一种方法,但无法弄清楚它是如何工作的.你是怎么用 pre_save() 做的?

Anyhow, I've been looking into pre_save() as another way to do this, but can't figure out how it works. How do you do it with pre_save()?

像吗

def pre_save(self):
     self.slug = title

我猜不是.执行此操作的代码是什么?

I'm guessing no. What is the code to do this?

谢谢!

推荐答案

您很可能指的是 django 的 pre_save 信号.你可以这样设置:

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)

如果您没有在装饰器中包含 sender 参数,例如 @receiver(pre_save, sender=MyModel),则会为所有模型调用回调.

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

您可以将代码放在应用执行期间解析的任何文件中,models.py 是一个很好的地方.

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.

这篇关于使用 pre_save() 填充 Django 字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆