Add onetoone field to all users, django

Viewed 46

In the middle of the project, I was faced with the fact that I needed to expand my user model. Since it is very problematic to create a custom model at the moment, I decided to use the onetoone field and everything is successful, but there is a question. I would like to add a relationship to my user model proxy for existing users and set permissions for them. How can I do that? I need to set start value for all users

class UserPermission(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    start = models.BooleanField(default=True)
    professional = models.BooleanField()
    team = models.BooleanField()
    last_update = models.DateTimeField()

1 Answers

If you can do this from your shell, then follow only step 2. If you want to do it from a migrations file, follow steps 1-3. (From the shell is easier).

  1. In your terminal: run python manage.py make migrations app_name --empty

  2. Add a function in your new migrations file that does the work you want to do for existing users.

def add_perms(apps, schema_editor):
    UserPermissions.objects.bulk_create([UserPermissions(user_id=user_id) for user_id in User.objects.values_list("id", flat=True)], ignore_conflicts=True)

If you're doing this from your shell, you don't need the function itself. Just what it runs. UserPermissions(user_id=user_id) is just a base and you should add the defaults alongside that user_id part.

  1. In the operations list, write:
operations = [
    migrations.RunPython(add_perms)
]
Related