Django是否只有在用户创建时(而不是每次保存时)才做某事?

时间:2018-07-27 08:16:21

标签: django django-models django-allauth

我正在努力解决通过django allauth社交登录批量导入用户信息的问题。我通过创建一个单独的模型来做到这一点,我可以将用户信息csv上传到该模型中,该模型将在用户首次登录后移植到真实表中。本质上,它将根据用户的电子邮件为其预先填充用户的信息。我遇到的问题是,因为我使用的是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)

2 个答案:

答案 0 :(得分:3)

尝试一下

@receiver(post_save, sender=User)
def imported_info_update(sender, instance=None, created=False, **kwargs):
    if created:
        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

答案 1 :(得分:1)

post_save函数有一个附加参数:created [Django-doc]。它是一个布尔值,用于指定是否已创建对象。您可以这样写:

@receiver(post_save, sender=User)
def imported_info_update(sender, instance, created=None, **kwargs):
    if created:
        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)

请注意,在某些情况下可以绕过信号。由于存在构造行而不调用.save()的方法。

例如,如果您要使用Model.objects.bulk_create(collection),它将.save()的项目调用collection,因此也不会{{1} },触发器也不会触发。