Django model inheritance: create sub-instance of existing instance (downcast)?

前端 未结 7 1912
野的像风
野的像风 2020-11-29 01:52

I\'m trying to integrate a 3rd party Django app that made the unfortunate decision to inherit from django.contrib.auth.models.User, which is a big no-no for plu

7条回答
  •  抹茶落季
    2020-11-29 02:26

    @guetti's answer worked for me with little update => The key was parent_ptr

    parent_object = parent_model.objects.get(pk=parent_id)  
    new_child_object_with_existing_parent = Child(parent_ptr=parent, child_filed1='Nothing')
    new_child_object_with_existing_parent.save()
    

    I wanted to create entry in my profile model for existing user, my model was like

    from django.contrib.auth.models import User as user_model
    class Profile(user_model):
         bio = models.CharField(maxlength=1000)
         another_filed = models.CharField(maxlength=1000, null=True, blank=True)
    

    At some place I needed to create profile if not exists for existing user so I did it like following,

    The example that worked for me

    from meetings.user import Profile
    from django.contrib.auth.models import User as user_model
    
    user_object = user_model.objects.get(pk=3)  
    profile_object = Profile(user_ptr=user_object, bio='some')
    profile_object.save()
    

提交回复
热议问题