我正在尝试使用从URL获取的kwargs在ViewSet中创建新对象。我尝试传递带有上下文的那些,但是需要先调用is_valid
才能保存。我尝试使用SerializerMethodField
,但这被m2m要求阻止。我正在尝试使用ModelSerializer
,我不想让数据变得可变。
def create(self, request, *args, **kwargs):
project_id = kwargs.get('project_id')
startup_id = kwargs.get('startup_id')
self.user = request.user
self.startup = Startup.objects.get(pk=startup_id)
self.project = Project.objects.get(pk=project_id)
serializer = RatingSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
print(serializer.data)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
在我的模型中,我有外键和m2m字段。
rating = IntegerField(choices=rating_choices)
project = ForeignKey(Project, on_delete=models.CASCADE)
user = ManyToManyField(User, related_name='users')
startup = ManyToManyField(Startup, related_name='users')
def __str__(self):
return 'Rating {}'.format(self.rating)
我的问题是如何将这些数据传递给序列化程序。