我今天在我的项目中添加了一个新的 UserProfile 模型。
class UserProfile(models.Model):
user = models.OneToOneField(User)
...
def __unicode__(self):
return u'Profile of user: %s' % (self.user.username)
class Meta:
managed = True
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
上面的代码将为每个新创建的用户创建一个用户配置文件。
但如何为每个现有用户创建用户配置文件自动地?
Thanks
您可以循环遍历现有用户,然后调用get_or_create()
:
for user in User.objects.all():
UserProfile.objects.get_or_create(user=user)
你可以把它放在一个数据迁移 https://docs.djangoproject.com/en/1.9/topics/migrations/#data-migrations如果您愿意,或者在 shell 中运行代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)