Django Multi-Table Inheritance VS Specifying Explicit OneToOne Relationship in Models

后端 未结 5 2072
萌比男神i
萌比男神i 2021-01-30 11:53

Hope all this makes sense :) I\'ll clarify via comments if necessary. Also, I am experimenting using bold text in this question, and will edit it out if I (or you) find it distr

5条回答
  •  无人共我
    2021-01-30 12:33

    I'd like to expand on the solution by @thornomad.

    Extending Django's User class directly can cause all kinds of trouble with the internal django.auth mechanisms. What I've done in a similar situation is precisely what @thornomad suggests - I made my own UserProfile model linked one-to-one with the Django User model, in which I held additional user data and from which I inherited models for different types of users.

    Something to fit what you described:

    class UserProfile(models.Model):
        user = models.OneToOneField(User, blank=True, related_name='profile')
        class Meta:
            abstract = True
    
    
    class PositionHolderUserProfile(UserProfile):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        landline = models.CharField(blank=True, max_length=20)    
        mobile = models.CharField(blank=True, max_length=20)
        created_by = models.ForeignKey(PositionHolderUserProfile, editable=False, blank=True, related_name="created_users")    
        modified_by = models.ForeignKey(PositionHolderUserProfile, editable=False, blank=True, related_name="modified_users")
    
    class Principal(PositionHolderUserProfile):
        branchoffice = models.ForeignKey(BranchOffice)
    
    class Administrator(PositionHolderUserProfile):
        superior = models.ForeignKey(Principal, related_name="subordinates")
        province = models.ForeignKey(Province)
    
    class Coordinator(PositionHolderUserProfile):
        superior = models.ForeignKey(Administrator, related_name="subordinates")
    
    
    class Company(UserProfile):
        name = models.CharField(max_length=50)
    
    class Product(models.Model):
        name = models.CharField(max_length=50)
        produced_by = models.ForeignKey(Company)
    
    class Buyer(UserProfile):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        products_bought = models.ManyToManyField(Product)
    

提交回复
热议问题