Django-为所有现有用户创建配置文件

时间:2020-06-06 13:09:18

标签: python django backend django-users django-3.0

我正在使用Django 3,这是我的用户个人资料模型

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from django.db.models.signals import post_save
from django.utils.text import slugify 
from django.db.models import signals

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=1000,blank=True)
    created_at = models.DateTimeField(default=datetime.now())
    slug = models.SlugField(blank=True)
    img = models.ImageField(upload_to='userimg/',default='userimg/avatar.png')

    def __str__(self):
        return "%s" % self.user

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(Profile, self).save(*args, **kwargs)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.get(user=instance)

post_save.connect(create_user_profile, sender=User)

def delete_user(sender, instance=None, **kwargs):
    try:
        instance.user
    except User.DoesNotExist:
        pass
    else:
        instance.user.delete()

signals.post_delete.connect(delete_user, sender=Profile)

问题在于函数create_user_profile仅为新用户创建配置文件,而不能为旧用户创建配置文件,那么我该如何解决?

1 个答案:

答案 0 :(得分:0)

您可以制作一个data migration。您使用以下方法创建一个:

python3 manage.py makemigrations --empty app_name

在其中将app_name替换为存储Profile模型的应用程序的名称。在迁移中,您可以制作Profile个模型:

from django.db import migrations
from django.conf import settings

def make_profiles(apps, schema_editor):
    User = apps.get_model(settings.AUTH_USER_MODEL)
    Profile = apps.get_model('app_name', 'Profile')
    profiles = [Profile(user=user) for user in User.objects.filter(profile=None)]
    Profile.objects.bulk_create(profiles)

class Migration(migrations.Migration):

    dependencies = [
        ('app_name', '1234_some_migration'),
    ]

    operations = [
        migrations.RunPython(make_profiles),
    ]

注意:与直接使用settings.AUTH_USER_MODEL [Django-doc]相比,通常最好使用User model [Django-doc]来引用用户模型。有关更多信息,请参见referencing the User model section of the documentation