我正在尝试创建一个 API 对象 Roster,它有一个成员列表作为子对象。但是,我不想通过部分更新名册对象来更新子对象——相反,我想要“添加成员”和“删除成员”的路由。
目标:
GET /Roster/{ROSTERID}
回复正文:
{
id: {roster id},
members: # members sub object is read only
[
{member subobject},
{member subobject},
...
],
}
POST /Roster/{RosterID}/AddMember
{
{member id},
{member id}, ...
}
然后是删除成员的类似操作。
注意:我希望能够传入现有的成员 ID。我不想在这里创建新成员。
我应该在文档中寻找什么才能添加路由来使用用户 ID 更新成员列表,而不必传入整个用户对象?
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class RosterSerializer(serializers.ModelSerializer):
members = serializers.ListField(
child=UserSerializer()
)
class Meta:
model = Roster
fields = ('id', 'name', 'members')
depth = 2
app/models.py
class Members(User):
on_pto = models.BooleanField(default=False)
class Roster(models.Model):
objects = models.Manager()
name = models.CharField(max_length=80, blank=True, default='', unique=True, null='')
members = models.ForeignKey(
Members,
limit_choices_to={'on_pto': False},
blank=True,
null=True,
related_name='members',
on_delete=models.CASCADE
)
views.py
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all().order_by('-id')
serializer_class = GroupSerializer
class RosterViewSet(viewsets.ModelViewSet):
""""""
queryset = Roster.objects.all().order_by('-id')
serializer_class = RosterSerializer
12345678_0001
相关分类