Django: UserProfile with Unique Foreign Key in Django Admin

白昼怎懂夜的黑 提交于 2019-11-28 08:36:48
KillianDS

It is normal that django will create the admin instance afterwards, as the saving consists always of something like this:

  1. Create User object
  2. Create Profile object (can't be before because it points to a user).

When saving the User object the django ORM cannot know the create profile object will come after it so it will not delay the post_save signal in any way (doesn't even make sense).

The best way to handle this (imho) if you want to keep the post_save signal, is to override the save method of UserExtension to something like this:

def save(self, *args, **kwargs):
    try:
        existing = UserExtension.objects.get(user=self.user)
        self.id = existing.id #force update instead of insert
    except UserExtension.DoesNotExist:
        pass 
    models.Model.save(self, *args, **kwargs)

Note that this does force every insert that points to the same user as an existing object to become an update, this can be unexpected behaviour for other parts of code.

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