1

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?

irene
  • 2,085
  • 1
  • 22
  • 36

1 Answers1

2

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.

Shubhanshu
  • 975
  • 1
  • 8
  • 21
  • Thanks Shubhanshu! Is there any way to write this code without having to write them down in a shell? Something like `python myfile.py` instead of having to type `python` and then writing down the code line by line? EDIT: Found the answers right here. Apparently, it's not standard practice! http://stackoverflow.com/questions/16853649/executing-python-script-from-django-shell – irene Nov 02 '16 at 07:48
  • Doing it in a shell is a terrible idea, if you have a proper development setup, not only does everyone in your team need to do it, but you also then need to do it on all servers. – Sayse Nov 02 '16 at 08:19
  • @Sayse You mentioned a custom migration, but may I know how to go about it? I'm relatively new to Django, and don't know much about migrations beyond `python manage.py makemigrations` and `python manage.py migrate`. Thanks! – irene Nov 02 '16 at 12:39
  • @irene - [Data Migrations](https://docs.djangoproject.com/en/1.10/topics/migrations/#data-migrations) – Sayse Nov 02 '16 at 13:00