I have an issue with my original design and need some help.
I have an Employee object that has a OneToOneField relationship to the User object.
My original plan for how a staff member would create a new Employee was:
- Login to Django Admin area
- Create new User
- Go back into main website application
- Create new Employee with form, choosing the newly created User in the username field
However, this has proved to be cumbersome and I need to improve the design.
The new idea for a staff member creating an Employee is:
- Go into main website application
- Create new Employee with form
- Use signals.py to automatically create a new User and assign it to the username field on the Employee object
My issue is that when I try to add a new Employee through the form, I cannot even get to the signals.py code to create the new User. This is because the Employee object throws an error that the username field is required, obviously due to the primary_key=True
models.py
class Employee():
username = models.OneToOneField(User, on_delete=models.RESTRICT, primary_key=True)
first_name = models.CharField(max_length=50, blank=True, default='')
last_name = models.CharField(max_length=50, blank=True, default='')
What is my best option at this point?
I can try something like removing the primary_key=True from the Employee object, and allowing it to be blank:
username = models.OneToOneField(User, on_delete=models.RESTRICT, blank=True, null=True)
But that gives the following error in the terminal/console:
It is impossible to add a non-nullable field ‘id’ to employee without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:
1-Provide a one-off default now (will be set on all existing rows with a null value for this column)
2-Quit and manually define a default value in models.py.
It makes sense that this error would occur, because if I remove the primary key on that table, it needs to know what makes the rows unique.
To further compound the issue, this application is already deployed in production, so I can’t just wipe out the database and start fresh.
How can I remove the requirement for that username field, or circumvent it to be able to automatically create the new User upon creation of the new Employee record?