Django - Multiple User Profiles

前端 未结 3 456
小鲜肉
小鲜肉 2021-01-29 21:27

Initially, I started my UserProfile like this:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    use         


        
3条回答
  •  醉梦人生
    2021-01-29 21:38

    Could be worth to try using a through field. The idea behind it is to use the UserProfile model as through model for the CorpProfile or IndivProfile models. That way it is being created as soon as a Corp or Indiv Profile is linked to a user:

    from django.db import models
    from django.contrib.auth.models import User
    
    class UserProfile(models.Model):
        user = models.ForeignKey(User)
        profile = models.ForeignKey(Profile, related_name='special_profile')
    
    class Profile(models.Model):
        common_property=something
    
    class CorpProfile(Profile):
        user=models.ForeignKey(User, through=UserProfile)
        corp_property1=someproperty1
        corp_property2=someproperty2
    
    class IndivProfile(Profile):
        user=models.ForeignKey(User, through=UserProfile, unique=true)
        indiv_property1=something
        indiv_property2=something
    

    I think that way it should be possible to set AUTH_PROFILE_MODULE = 'accounts.UserProfile', and every time you create either a CorpProfile or a IndivProfile that is linked to a real user a unique UserProfile model is created. You can then access that with db queries or whatever you want.

    I haven't tested this, so no guarantees. It may be a little bit hacky, but on the other side i find the idea quite appealing. :)

提交回复
热议问题