How to set the admin user ID as a foreign key in Django another table
To set the admin user ID as a foreign key in another table, you can use Django's built-in User
model from the django.contrib.auth.models
module. Here's an example:
-
Open the file containing the model where you want to set the foreign key, typically
models.py
in your app directory. -
Import the necessary modules:
from django.contrib.auth.models import User
from django.db import models
Define your model and set the foreign key relationship with the
User
model:
class YourModel(models.Model):
admin_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
# Other fields of your model
In the above code, the admin_user
field is defined as a foreign key to the User
model. The on_delete
parameter specifies the behavior when the referenced user is deleted. In this case, models.SET_NULL
is used to set the admin_user
field to NULL
if the referenced user is deleted. You can adjust this behavior according to your requirements.
- Generate and apply the necessary database migrations to create the foreign key relationship. Run the following commands:
python manage.py makemigrations
python manage.py migrate
These commands will create the migration files and apply the changes to the database.
Now, you can access the admin user associated with a record in the other table through the admin_user foreign key field.
Note: If you're using a custom user model instead of Django's default User model, make sure to update the import statement and reference your custom user model in the foreign key field definition.