使用pre_save()填充django字段? [英] Populating django field with pre_save()?
问题描述
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中时如何创建和存储一个s,如果没有,请纠正我!
无论如何,我一直在寻找pre_save()作为另一种方式做到这一点,但不能弄清楚它是如何工作的。如何使用pre_save()?
就像
def pre_save(self):
self.slug = title
没有。
很可能是指 django的
pre_save
信号。您可以设置如下: 来自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)
,将为所有模型调用回调。
在您的应用程序执行期间解析的任何文件中的代码, models.py
是一个很好的地方。
class TodoList(models.Model):
title = models.CharField(maxlength=100)
slug = models.SlugField(maxlength=100)
def save(self):
self.slug = title
super(TodoList, self).save()
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!
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()?
is it like
def pre_save(self):
self.slug = title
I'm guessing no. What is the code to do this?
Thanks!
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.
这篇关于使用pre_save()填充django字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!