我正在尝试解决通过 django allauth 社交登录批量导入用户信息的困难。我通过创建一个单独的模型来做到这一点,我可以将用户信息上传到该模型,该模型将在用户第一次登录后移植到真实的表中。本质上,它将根据用户的电子邮件预先填充用户的信息。我遇到的问题是,因为我使用的是 post_save
发送器,所以每次用户更改其个人资料的某个方面时,它都会尝试更新信息。我的问题是,用户信息合法更改,但未在 UserData 表中更新(该表仅用于初始导入),它只会更改回来。我很好奇有什么想法可以解决这个问题。谢谢!
@receiver(post_save, sender=User)
def imported_info_update(sender, instance, **kwargs):
imported_info = UserData.objects.get(email=instance.email)
job = Jobs.objects.get(job=imported_info.department)
location = Locations.objects.get(location=imported_info.team)
school = Schools.objects.get(school=imported_info.school)
UserProfile.objects.update_or_create(user_id=instance.id,
job=job,
location=location,
school=school)
最佳答案
试试这个
@receiver(post_save, sender=User)
def imported_info_update(sender, instance=None, <b>created=False,</b> **kwargs):
<b>if created:</b>
imported_info = UserData.objects.get(email=instance.email)
job = Jobs.objects.get(job=imported_info.department)
location = Locations.objects.get(location=imported_info.team)
school = Schools.objects.get(school=imported_info.school)
UserProfile.objects.update_or_create(user_id=instance.id,
job=job,
location=location,
school=school)
引用:https://docs.djangoproject.com/en/2.0/ref/signals/#post-save
关于django - Django 是否有办法仅在用户创建时(而不是每次保存时)执行某些操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51553727/