型号:
class Thread(models.Model):
"""Thread model for messages."""
participants = models.ManyToManyField(to=User, verbose_name=_("Participants"))
created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("Created"))
updated_at = models.DateTimeField(auto_now=True, verbose_name=_("Updated"))
我有这个序列化程序:
class UserSerializer(serializers.ModelSerializer):
"""Serialize User model to get data from ManyToMany field to use in Thread participants."""
class Meta:
model = User
fields = ("id", "email")
class ThreadSerializer(serializers.ModelSerializer):
"""Serializer for create, get, edit, delete Thread."""
participants = UserSerializer(read_only=True, many=True)
class Meta:
model = Thread
fields = ("id", "participants", "created_at", "updated_at")
和视图:
class ThreadListCreate(generics.ListCreateAPIView):
"""
Get threads list with participants details.
Creates a new thread with two participants.
"""
permission_classes = (AllowAny,)
queryset = Thread.objects.all()
serializer_class = ThreadSerializer
我需要在";参与者";,我该怎么办?此外,为了将新用户分配给"用户";参与者";我只需要键入";id";,类似下面的代码:
{
"participants": [
{"id": 1},
{"id": 4}
]
}
现在作为上面POST代码的结果,我得到了这个:
{
"id": 28,
"participants": [],
"created_at": "2022-02-16T18:22:17.524911Z",
"updated_at": "2022-02-16T18:22:17.524911Z"
}
- 也许您想将视图集从
ThreadListCreate
重命名为ThreadListCreateViewSet
(更可读(,也许您可以直接使用ModelSerailizer
,因为它具有您所需要的所有功能 - 最好只是拆分序列化程序(一个仅用于创建目的(
我会做一些类似的事情
ViewSet
class ThreadListCreateViewSet(ModelViewset):
permission_classes = (AllowAny,)
queryset = Thread.objects.all()
serializer_class = ThreadSerializer
create_serializer_class = CreateThreadSerializer
def get_serializer_class(self):
if self.action == "create":
return self.create_serilaizer_class
return self.serializer_class
序列化程序
class CreateThreadSerializer(serializers.ModelSerializer):
participants = UserSerializer(many=True)
def create(self, validated_data):
instance = Thread.objects.create()
for user in validated_data["participants"]:
instance.participants.add(user)
instance.save()
return instance
这就是我要做的。。。希望它对你有用。