首先看看我的模型:
from django.contrib.auth.models import User
class Group(models.Model):
person = models.ManyToManyField(
User,
through='PersonGroup',
related_name='person_of_the_group'
)
class PersonGroup(models.Model):
group = models.ForeignKey(
Group,
on_delete=models.CASCADE,
related_name='group_person_of_group'
)
person = models.ForeignKey(
User,
on_delete=models.CASCADE
)
这是我的观点:
class AddGroupMembers(CreateAPIView):
serializer_class = PersonGroupSerializers
queryset = Group.objects.all()
lookup_field = 'pk'
def create(self, request, *args, **kwargs):
# Make requst data mutable
if not request.data._mutable:
request.data._mutable = True
request.data['person'] = request.user.pk
request.data['group'] = kwargs['pk']
serializer = PersonGrouperializers(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
这是我的序列号:
class PersonGroupSerializers(ModelSerializer):
class Meta:
model = PersonGroup
fields = '__all__
我希望网址pk会变成pk,
http://127.0.0.1:8000/mess/api/v1/mess/<int:mess.pk>/
我希望在到达终点时,我应该能够创建PersonGroup
,如果您看到我的视图,便会知道我是如何填充此表的。
我的意思是,端点网址将由Group
pk
中的任何一个标识,但在那里我应该能够PersonGroup
希望你明白了,有人可以告诉我如何实现吗?