[英]Django pre_save, instance is None
I am writing the pre_save method to create the slug for model, for some reason my instance is none.我正在编写 pre_save 方法来为 model 创建 slug,由于某种原因,我的实例没有。
@receiver(pre_save, sender=Employee)
def pre_save_employee_receiver(sender, instance, *args, **kwargs):
slug = slugify(" ".join([instance.name, instance.surname, instance.id]))
instance.slug = slug
Error is:错误是:
File "E:\Work\hire_handler\employees\models.py", line 60, in pre_save_employee_receiver
slug = slugify(" ".join([instance.name, instance.surname, instance.id]))
TypeError: sequence item 2: expected str instance, NoneType found
No , the instance
is not None
, the primary key ( instance.id
) is None
.不, instance
不是None
,主键( instance.id
)是None
。
That makes perfect sense, before creating the object at the database side, the item has no primary key, since database dispatches a primary key.这很有意义,在数据库端创建 object 之前,该项目没有主键,因为数据库调度了一个主键。
If you thus want to work with a primary key, you need to work with a post_save
item, furthermore likely the id
is an int, so it will still not work, since ' '.join()
can not join integers.因此,如果您想使用主键,则需要使用post_save
项,而且id
很可能是一个 int,所以它仍然不起作用,因为' '.join()
不能连接整数。
You can use a post_save
trigger, and save it again, but that will result in making two queries when you create a new Employee
:您可以使用post_save
触发器,然后再次保存,但这将导致在创建新Employee
时进行两次查询:
@receiver(post_save, sender=Employee)
def post_save_employee_receiver(sender, instance, created, *args, **kwargs):
if created:
instance.slug = slugify(f'{instance.name} {instance.surname} {instance.pk}')
instance.save()
Furthermore signals are usually a bit of an antipattern , especially since when you for example perform .bulk_create()
, .update()
, etc. the signals are not triggered.此外,信号通常有点反模式,尤其是当您执行.bulk_create()
、 .update()
等时,信号不会被触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.