Django using the auth_user table in relationships

Viewed 50

I'd like to use the auth_user table in one-to-many and many-to-many relationships.

  • Is this a bad idea?
  • Can I do it?
  • How do I do it?

Everything is happening through Admin. So, I just need the models.

I got it working...

class Profile(models.Model):
    profile_name = models.CharField(max_length=100)
    profile_url = models.URLField(max_length=255)
    def __str__(self):
        return self.profile_name  
 

class Teacher(AbstractUser):
    profile = models.ManyToManyField(Profile, through='TeacherProfile')
    def __str__(self):
        return self.email

class TeacherProfile(models.Model):
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    profile_url = models.URLField(max_length=255)
    class Meta:
        unique_together = (('teacher', 'profile'),)
    def __str__(self):
        return f'{self.teacher}, {self.profile}' 

desc vcm_teacher;

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| password     | varchar(128) | NO   |     | NULL    |                |
| last_login   | datetime(6)  | YES  |     | NULL    |                |
| is_superuser | tinyint(1)   | NO   |     | NULL    |                |
| username     | varchar(150) | NO   | UNI | NULL    |                |
| first_name   | varchar(150) | NO   |     | NULL    |                |
| last_name    | varchar(150) | NO   |     | NULL    |                |
| email        | varchar(254) | NO   |     | NULL    |                |
| is_staff     | tinyint(1)   | NO   |     | NULL    |                |
| is_active    | tinyint(1)   | NO   |     | NULL    |                |
| date_joined  | datetime(6)  | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

I had to add this line in settings.py

AUTH_USER_MODEL = 'vcm.Teacher'
drop database vcm;
create database vcm;

find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc"  -delete

python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py createsuperuser

There's some info here How to Extend Django User Model

0 Answers
Related