I have a conventional project that stores users in auth_user django table.
Later, I decided to implement a profiles
app. The views.py
code is below
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
I do makemigrations
and migrate
. The table is created with empty data, i.e., previous users that exist in auth_user
were not populated in the profiles_profile
table.
How can I populate old data in my new table?
Thanks
CodePudding user response:
Get all the objects from user models and save into Profile models using shell. It's the easiest way.
python manage.shell
then import both models User and Profile
for user in User.objects.all():
profile=Profile()
profile.user=user
profile.save()
CodePudding user response:
This is the way to do it: in the terminal type:
python manage.py makemigrations --empty profiles
I use profiles because that's my app_name.
This creates a file in the migrations folder of your app
Mine for example is
0005_auto_20221101_1518.py
In this file type the following:
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('profiles', 'Profile')
profiles = [Profile(user=user) for user in User.objects.filter(profile=None)]
Profile.objects.bulk_create(profiles)
class Migration(migrations.Migration):
dependencies = [
('profiles', '0004_merge_20221101_1507'),
]
operations = [
migrations.RunPython(make_profiles),
]
ok here you can figure it out easily. In my case Profile is the model and profiles is the app_name. 0004_merge_20221101_1507
corresponds to the previous migration file. This is automatically set so nothing to worry about, however if you play around with your migration files, then this one should be the previous one in the list...usually identified in order by 0001.., 0002, ...0003, 0004, and so on.
After that just makemigrations
and migrate
. And that's it... however, what if you have a unique field in your new table, for example a slug based on the first_name and last_name of the user. You may have a problem as two users may share the same slug field. In this case migration will show an error.
There are different ways to solve this out there....but is not within the scope of this answer. Cheers