我正在尝试创建用户,其中用户模型有两个用户配置文件,例如教师和学生。 在创建用户时,我还想在Teacher或Student配置文件中创建User实例。
这是我的串行器类:
class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('id', 'user_id') class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = ('id', 'user_id') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'username', 'password', 'email', 'user_type' ) extra_kwargs = { 'password': {'write_only': True}, } def create(self, validated_data): user = User.objects.create_user(**validated_data) return user这是自定义寄存器视图:
class CreateUserView(CreateAPIView): model = User permission_classes = [ permissions.AllowAny # Or anon users can't register ] serializer_class = UserSerializer现在,我可以创建用户,但根据user_type参数创建用户配置文件对我来说是一个挑战。
所以,如果user_type是student ,我还需要为StudentProfile创建User实例(学生资料表中的新行)
I am trying to create user, where User model has two User profiles, e.g. Teacher and Student. At the time of creating user, I want to create User instance in Teacher or Student profile also.
Here's my Serializer classes:
class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('id', 'user_id') class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = ('id', 'user_id') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'username', 'password', 'email', 'user_type' ) extra_kwargs = { 'password': {'write_only': True}, } def create(self, validated_data): user = User.objects.create_user(**validated_data) return userHere's the custom register view:
class CreateUserView(CreateAPIView): model = User permission_classes = [ permissions.AllowAny # Or anon users can't register ] serializer_class = UserSerializerRight now, I am able to create User and but creating user profile according to the user_type parameter is a challenge for me.
So, if user_type is student, I need to create User instance for the StudentProfile as well(a new row in student profile table)
最满意答案
也许你可以添加简单的条件?
def create(self, validated_data): user = User.objects.create_user(**validated_data) if validated_data('user_type') == 'student': Student.objects.create(user_id=user.id) else: Teacher.objects.create(user_id=user.id) return userMay be you can add simple if condition?:
def create(self, validated_data): user = User.objects.create_user(**validated_data) if validated_data('user_type') == 'student': Student.objects.create(user_id=user.id) else: Teacher.objects.create(user_id=user.id) return user更多推荐
发布评论