lord stock
lord stock

Reputation: 1211

How do I Save and create Two Model user at same time in django?

I have following models Users and Teacher User model is inherited from AbstractBaseUser and Teacher is one to one relation with User. Below is Teacher User Model.

class TeacherUser(BaseModel):
    user = models.OneToOneField(User, on_delete=models.CASCADE, )
    faculty = models.CharField(max_length=100)
    faculty_code = models.CharField(max_length=100)
    is_full_time = models.BooleanField(default=False)
    joined_date = models.DateField()

    objects = TeacherUserManager()

Now problem is I want the only one form to be filled by teacher while registering the teacher user.So I tried this in TeacherSerialzier.

class CreateTeacherUserSerializer(TeacherUserSerializer):
    class Meta(TeacherUserSerializer.Meta):
        fields = (
            'faculty',
            'faculty_code',
            'is_full_time',
            'joined_date'
        )


class CreateUserSerializer(UserSerializer):
    techer = CreateTeacherUserSerializer(source='teacheruser')

    class Meta(UserSerializer.Meta):
        fields = (
            'username',
            'fullname',
            'email',
            'phone_number',
            'password',
            'techer'
        )
        extra_kwargs = {
            'password': {
                'write_only': True,
                'style': {'input_type': 'password'}
            }
        }

The default form given is as below (image).

Form for user and teacher user

Now on my views.py I tried creating my user and teacher users

class CreateUserView(generics.CreateAPIView):
    serializer_class = serializers.CreateUserSerializer
    permission_classes = (AllowAny,)

    def perform_create(self, serializer):
        return usecases.CreateUserUseCase(serializer=serializer).execute()

and The main logic section where I tried creating users is as below

usecases.py

User = get_user_model()


class CreateUserUseCase:
    def __init__(self, serializer):
        self._serializer = serializer
        self._data = serializer.validated_data

    def execute(self):
        self._factory()

    def _factory(self):
        teacher_user = self._data.get('teacheruser')

By default when I fill the above image form I get ordered dictionary and there comes another teacheruser dictionary. I can access the teacheruser dictionary using self._data.get('teacheruser') but I am not able to pop the teacher user from ordered dictionary using self._data.pop('teacheruser') Any help or any suggestion regarding saving two users i.e teacher user and user at same time will be so much of help.

Upvotes: 0

Views: 176

Answers (1)

Shubham Agrawal
Shubham Agrawal

Reputation: 427

I am written code snippet you can refer from it

serializer :-

from django.db import transaction

class CreateUserSerializer(ModelSerializer):
    techer = CreateTeacherUserSerializer(source='teacheruser')

    class Meta(UserSerializer.Meta):
        fields = (
            'username',
            'fullname',
            'email',
            'phone_number',
            'password',
            'techer'
        )
        extra_kwargs = {
            'password': {
                'write_only': True,
                'style': {'input_type': 'password'}
            }
        }
        
    def create(self, validated_data):
        teacher_data = validated_data.pop("techer")
        with transaction.atomic():
            user = super(CreateUserSerializer, self).create(validated_data)
            teacher_data["user"] = user
            TeacherUser.objects.create(**teacher_data)
            return user

view

class CreateUserView(generics.CreateAPIView):
    serializer_class = serializers.CreateUserSerializer
    permission_classes = (AllowAny,)

Upvotes: 1

Related Questions