django:自动为现有用户创建用户配置文件 [英] django: create user profile for existing users automatically

查看:89
本文介绍了django:自动为现有用户创建用户配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在项目中添加了一个新的UserProfile模型。

I added a new UserProfile Model to my project today.

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)

上面的代码将为每个新创建的用户创建一个用户个人资料。

The above code will create a user profile for each new created user.

但是如何为每个现有用户自动创建用户资料

But how to create the user profile for each existing user automatically?

谢谢

推荐答案

您可以遍历现有用户,并调用 get_or_create()

You can loop through the existing users, and call get_or_create():

for user in User.objects.all():
    UserProfile.objects.get_or_create(user=user)

您可以将其放在数据迁移(如果需要),或者在外壳中运行代码。

You could put this in a data migration if you wish, or run the code in the shell.

这篇关于django:自动为现有用户创建用户配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆