1

您好,我是 django django rest 框架和 djoser 的新手,我只是想知道。如何将 djoser 与多个扩展用户一起使用。下面是我的模型、序列化器和视图。我在互联网上真的找不到任何东西。Djoser 文档没有关于多个用户的任何内容。我应该只使用 Django Rest Framework 的内置令牌身份验证吗?

模型:我正在尝试使用学生模型和教师模型继承用户(如下所示)。我希望 djoser 使用这两个模型来创建用户。

from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
# Create your models here.

class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='student')
    age = models.IntegerField()
    address = models.CharField(max_length=200)

    def __str__(self):
        return self.user.username

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='teacher')
    description = models.TextField()

    def __str__(self):
        return self.user.username

class Course(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()
    price = models.FloatField(default=25.00)

    def __str__(self):
        return self.name

序列化器:

我的序列化程序还没有完成,但我仍然需要重写 create 和 update 方法。

from rest_framework import serializers
from api.models import *
from django.contrib.auth.models import User

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ('age', 'address')

class StudentUserSerializer(serializers.ModelSerializer):

    student = StudentSerializer()

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name', 'student')
        extra_kwargs = {'password': {'write_only': True, 'required': True}}

class TeacherSerializer(serializers.ModelSerializer):
    class Meta: 
        model = Teacher
        fields = ('description', )

class TeacherUserSerializer(serializers.ModelSerializer):

    teacher = TeacherSerializer()

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name', 'teacher') 
        extra_kwargs = {'password': {'write_only': True, 'required': True}}

class CourseSerializer(serializers.ModelSerializer):

    class Meta:
        model = Course
        fields = '__all__'

意见:

除了我的观点,我还必须为这些观点设置权限。

from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from api.serializers import *
from api.models import *
from django.contrib.auth.models import User
# Create your views here.

class CourseView(ModelViewSet):
    serializer_class = CourseSerializer
    queryset = Course.objects.all()

class StudentView(ModelViewSet):
    serializer_class = StudentUserSerializer
    queryset = User.objects.all()

class TeacherView(ModelViewSet):
    serializer_class = TeacherUserSerializer
    queryset = User.objects.all()
4

1 回答 1

0

覆盖 和的ModelViewset方法perform_create()来创建一个用户对象。TeacherViewStudentView

于 2021-03-19T18:47:50.283 回答