简体   繁体   中英

django foreign key relationships

models.py

class Hub(models.Model):
    name = models.CharField(max_length=150)

    def __str__(self):
        return self.name


class User(AbstractUser):
    is_client = models.BooleanField(default=False)
    is_trainer = models.BooleanField(default=False)
    username = models.CharField('username', max_length=150, unique=True)
    email = models.EmailField(unique=True)
    hub = models.ForeignKey(Hub, on_delete=models.CASCADE, blank=True, null=True)
    hub_position = models.CharField(max_length=150, default="")
    mentor = models.ForeignKey('self', on_delete=models.CASCADE, blank=True,null=True)
    terms = models.BooleanField(blank=True, default=False)
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'terms']

    def get_absolute_url(self):
        return reverse('student:dashboard', kwargs={'pk': self.pk})

Confused on how to design the models here. Each User can belong to exactly one Hub.A hub has one leader, many excoms and many members ,all of them belongs to User .The hubs are added from the admin side.Leader can accept hub joining requests from excoms and members.

I'd add the user position as a choice field to the User , so you get a nice select box in the Admin.

class User(AbstractUser):
    USER_POSITIONS = ((0, 'Regular'), (1, 'Leader'), (2, 'Excom'))

    hub = models.ForeignKey(Hub, on_delete=models.CASCADE, blank=True, null=True)
    hub_position = models.IntegerField(default=0, choices=USER_POSITIONS, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM