How can I send signals from within Django migrations?

ε祈祈猫儿з 提交于 2019-12-01 15:32:10

You can't (and should not) do this because when your migration is executed, your UserDetails could be really different than when you wrote this migration. This is why django (and south) use "frozen models" which are identical to when you wrote the migration.

"Unfortunately", you have to freeze your signal code in your migration to keep the behaviour expected at the time you write the migration.

A simple exemple to understand why it's important to not use real models (or signals etc.) inside a migration :

Today, I could have this :

class UserDetails(models.Model):
    user = models.ForeignKey(...)
    typo_fild = models.CharField(...)

@receiver(signals.post_save, sender=django.contrib.auth.models.User)
def add_user_details(sender, instance, created, **kwargs):
    if created:
        UserDetails.objects.create(user=instance, typo_fild='yo')

Then, I have a data migration (called "populate_users") which create new users and I force the execution of add_user_details inside it. It's okay : it works today.

Tomorrow, I fix my typo_fild -> typo_field inside UserDetails and inside add_user_details. A new schema migration is created to rename the field in the database.

At this point, my migration "populate_users" will fail because when a new user will be created, it will try to create a new UserDetails with a field "typo_field" wich does not yet exist in the database : this field will only be rename in the DB with the next migrations.

So, if I want to keep a good migration wich will work at anytime, I have to copy the behaviour of add_user_details inside the migration. This freeze of add_user_details will have to use the frozen model UserDetails via apps.get_model("myapp", "UserDetails") and create a new UserDetails with the typo_fild which is frozen too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!