第一个代码:
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
第二个代码:
@receiver(post_save, sender=User)
def create_or_save_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
else:
instance.profile.save()
实际上他们的工作有什么不同吗?
后者只是将前者合并为一种方法。这实际上取决于它的用途。如果方法很复杂,有很多逻辑,我宁愿保存并创建单独的。但是,上面的用例似乎可以与最小的可读性问题相结合