Reputation: 531
I'm starting an app with django; i love it so far but i've trouble initializing my database. To sum up, i need a table user and a table role; a user has a FK to role. Upon creation a user must have this role set explicitly or defaulting to a default role 'Regular user'.
I could create the model without the database, then manually create the role, then add the default and migrate; but that does not look nice; I tried adding to the database in-between the two models definition but obviously it does not work as the tables are not created during the makemigration command.
Is there any way to achieve what I want ? Here is my current models if it helps; feel free to report any non-sense in this; i'm learning. Thx ;)
from django.db import models
class Role(models.Model):
name = models.CharField(max_length=100)
identifier = models.CharField(max_length=20)
ts_create = models.DateTimeField(auto_now_add=True)
ts_update = models.DateTimeField(auto_now=True, default=None, null=True)
def __str__(self):
return self.name
userRole = Role.objects.get_or_create(name="Regular user", identifier="USER")
adminRole = Role.objects.get_or_create(name="Administrator", identifier="ADMIN")
ownerRole = Role.objects.get_or_create(name="Owner", identifier="OWNER")
class User(models.Model):
username = models.CharField(max_length=100, unique=True)
user_type = models.ForeignKey(Role, related_name="user_type", on_delete=models.PROTECT, default=userRole)
roles = models.ManyToManyField(Role, related_name="roles", db_table="core_roles_assignations")
ts_create = models.DateTimeField(auto_now_add=True)
ts_update = models.DateTimeField(auto_now=True, default=None, null=True)
def __str__(self):
return self.username
def is_admin(self):
return self.user_type.identifier == "ADMIN"
owner = User.objects.get_or_create(username="Nindouja", user_role=Role.objects.first())
``` python
Upvotes: 1
Views: 2838
Reputation: 324
If you need inital data with your db, you can use dumpdata and loaddata.
Dumpdata(Use only during the first time, after manually adding the roles to the db)
mkdir myapp/fixtures
python manage.py dumpdata myapp --indent=2 --output=myapp/fixtures/
mydata.json
When you are migrating, you can use:
Loaddata
$ python manage.py migrate myapp && python manage.py loaddata mydata.json
Upvotes: 1
Reputation: 1458
You can try Signal
for save role when User created. https://docs.djangoproject.com/en/3.1/ref/signals/
Ideal is: when user created, check user have role or not. If dont have, add default role for it. It will work everytime you try create user. Example:
@receiver(post_save, sender= User)
def post_save_user(sender, instance, created, **kwargs):
if created:
roles = instance.roles.all() # check user have any roles
if not roles:
default_role = Role.objects.first()
instance.roles.add(default_role)
Upvotes: 1