简体   繁体   中英

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.

@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 .

That makes perfect sense, before creating the object at the database side, the item has no primary key, since database dispatches a primary key.

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.

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 :

@receiver(post_save, sender=Employee)
def post_save_employee_receiver(sender, instance, created, *args, **kwargs):
    if :
        instance.slug = slugify(f'{instance.name} {instance.surname} {instance.pk}')
        instance

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM