Django REST框架:ManyToMany关系

时间:2020-04-07 09:49:36

标签: python django django-rest-framework

我目前正在处理Django项目,对此我还很陌生,很难找到清晰的文档。

我的问题很简单,我想在创建模型时,通过ManyToMany关系自动关联另一个模型。

代码如下:

型号:

class Favorite(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=60, blank=False)
    estates = models.ManyToManyField(Estate, blank=True)

序列化器:

class FavoriteSerializer(serializers.ModelSerializer):
    estates = EstateSerializer(read_only=True, many=True)

    class Meta:
        model = Favorite
        fields = ['uuid', 'title', 'estates']

    def create(self, validated_data):
        instance = super(FavoriteSerializer, self).create(validated_data)
        instance.save()

        return instance

ViewSet:

class MyFavoriteEstatesListViewSet(viewsets.ModelViewSet):
    serializer_class = FavoriteSerializer

    def get_queryset(self):
        return Favorite.objects.filter(users__id=self.request.user.id)

我目前正在通过POST发送类似的内容:

{"title": "some title", "estate_uuid": "XXX"}

我只是想用我刚刚发送的UUID实例化我的Estate模型,并用

添加它
favorite.estates.add(estate)

我该如何实现?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为您可以尝试这样的事情:

class EstateField(serializers.RelatedField):
   def to_representation(self, obj):
       return EstateSerializer(obj).data

   def to_internal_value(self, data):
       return Estate.objects.get(pk=data)

class FavoriteSerializer(serializers.ModelSerializer):
    estates = EstateField(many=True, queryset=Estate.objects.all())

    class Meta:
        model = Favorite
        fields = ['uuid', 'title', 'estates']

我正在使用Custom Fields将数据表示为字典,但将输入作为uuid