2016-05-11 4 views
0

CommonUser(AbstractUser)と2人の子供、Professional(CommonUser)Client(CommonUser)という3つのモデルがあります。djangoのベースモデルから "Create"子モデル

私はdjango-rest-social-authを使ってFacebookやGoogleなどからユーザーを作成していますが、私の設定ではAUTH_USER_MODEL = 'users.CommonUser'と設定していますが、最初にソーシャル・ログインを使用してユーザーを作成するには2段階あるタイプのユーザーからの残りのデータを埋めるためのフォーム。

django-rest-social-authで作成されたCommonUserからClientインスタンスまたはProfessionalインスタンスを作成する必要があります。つまり、django-rest-social-authで作成されたCommonUserインスタンスを "移動" 2番目のステップフォームを送信した後、クライアントインスタンスまたはProfessionalインスタンスに認証します。

答えて

1

いくつかのテストや関連する検索の結果、解決策が見つかりました。 、私はクライアントまたはProfessionalユーザーを救うビューで、私が使用します私の場合は

common_user = CommonUser.objects.get(id=id) 
common_user.__class__ = Client 
common_user.save() 

EDIT

上記の方法は、安全でない二this議論を探します。

いくつかのより多くの検索をし、私は解決策基本的here

が見つかりました:

class CommonUser(AbstractUser): 
    # attributes... 

    @classmethod 
    def create_child(cls, child_class, attrs): 
     """ 
     Inputs: 
     - child_class: child class prototype 
     - attrs: dictionary of new attributes for child 
     """ 
     try: 
      id = attrs.pop('id', None) 
      common_user = CommonUser.objects.get(id=id) 
     except Exception as e: 
      raise e 
     parent_link_field = child_class._meta.parents.get(common_user.__class__, None) 
     attrs[parent_link_field.name] = common_user 
     for field in common_user._meta.fields: 
      value = getattr(common_user, field.name) 
      if value: 
       attrs[field.name] = value 
     s = child_class(**attrs) 
     s.save() 
     return s 


class Professional(CommonUser): 
    # attributes... 


class Client(CommonUser): 
    # attributes... 

をそして今、私は実行することができます。

>>> professional = CommonUser.create_child(Professional, {'id': 1}) 
>>> client = CommonUser.create_child(Client, {'id': 2}) 
関連する問題