我有一个Django REST API,其用户和课程模型定义为:
class User(AbstractBaseUser):
id = models.UUIDField(primary_key = True, default=uuid.uuid4)
username = models.CharField(blank=False, max_length=32, unique=True)
notes = models.ForeignKey('notes.Note', null=True, related_name='notes')
courses = models.ManyToManyField(Course, related_name='courses')
class Course(models.Model):
course_name = models.CharFIeld(max_length=64)
course_tutor = models.ForeignKey('authentication.User', related_name='tutor', blank=True)
course_students = models.ManyToManyField('authentication.User', editable=True, related_name='students')
我的序列化器定义如下
class UserSerializer(serializers.ModelSerializer):
notes = serializers.SerializerMethodField('get_notes_for_user')
courses = serializers.SerializerMethodField('get_courses_for_student')
def get_courses_for_student(self, obj):
# What do I do here??
def get_notes_for_user(self, obj):
queryset = Note.objects.all().filter(note_owner=obj)
return queryset.values()
class Meta:
model = User
fields = ('id', 'username', 'notes', 'courses')
class CourseSerializer(serializers.HyperlinkedModelSerializer):
course_students = serializers.HyperlinkedRelatedField(view_name='user-detail', lookup_field='pk', many=True, read_only=True)
class Meta:
model = Course
fields = ('course_name', 'course_tutor', 'course_students', )
我的问题是:我如何正确(和RESTful)将用户注册到课程? 我想到了一个中间模型,例如订阅,但我不知道正确的方法。
最终目的是拥有一个用户/课程/活动API,允许某些用户订阅" (因此中间订阅模型)到某个课程/活动。我对如何实现这一点感到不安,并会提出更多见解。
如果我没有提供足够的细节来解决这个问题,请告诉我们。我很乐意提供任何其他信息。