irene irene - 1 month ago 6
Python Question

Modifying User instances in Django already in database

Let's say I already have existing User instances in my database. Then, I just introduced a new model in my app:

class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
nickname = models.CharField(max_length=30, blank=True)


I want to create a UserProfile instance for every user. I know that signals can handle this upon something like User().save(). However, what do I do with the users already in my database?

Currently I handle it in
views.py
:

try:
user.profile.nickname = 'my_nickname'
except:
profile = UserProfile()
profile.user = user
profile.nickname = 'my_nickname'
profile.save()


But this makes the view quite long. Is there a better way to do it?

Answer

For users already in your database, you can run a script on your django shell.

python manage.py shell

Then:

>>from .models import *
>>from django.contrib.auth.models import User
>>users_without_profile = User.objects.filter(profile__isnull=True)
>>for user in users_without_profile:
....user.profile.nickname = 'your_choice_of_nickname'
....user.save()

Just a side note: doing a wild import like from .models import * is a bad practice, but I did it anyway just for illustration and also I didn't know you appname. Hence, import the appropriate models from the respective app.

Hope this helps you.