如何在Django Rest框架中使用Through模型制作可写的ManyToManyField? [英] How can I make a writable ManyToManyField with a Through Model in Django Rest Framework?

查看:38
本文介绍了如何在Django Rest框架中使用Through模型制作可写的ManyToManyField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含源产品"的Product类;我使用带有贯通模型的多对多字段来表示它(数据库表已经存在,这是我发现配置模型的唯一方法):

I have a Product class that has "source products"; I use a many-to-many field with a through model to represent it (the database tables already exist, and that's the only way I found to configure the models):

class Product(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    product_name = models.TextField()
    source_products = models.ManyToManyField('self', symmetrical=False, related_name='derived_products', through='Link', through_fields=('product', 'source'),)
    class Meta:
        db_table = 'product'
        managed = False

class Link(models.Model):
    product = models.ForeignKey('Product', models.CASCADE, db_column='uuid', related_name='source_links')
    source = models.ForeignKey('Product', models.CASCADE, db_column='source_uuid', related_name='+')
    class Meta:
        db_table = 'link'
        unique_together = (('product', 'source'),)
        managed = False

我的序列化器简直太简单了:

My serializer is dead simple:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('uuid', 'product_name', 'source_products', )

GET请求返回:

{
    "product_name": "dummy.fra",
    "source_products": [
        "17b021e7-3d6b-4d29-a80b-895d62710080"
    ],
    "uuid": "48c5a344-877e-4e3f-9a4b-2daa136b68fe"
}

ManyToManyFields与通过模型是只读的,如何创建包含产品之间链接的产品?我想发送一个POST请求,该请求的格式与GET响应的格式相同(即,一个 source_products 字段,其中列出了现有产品的UUID).

The since ManyToManyFields with a Through Model are read-only, how do I go about to create a product including the link between products? I'd like to send a POST request that follows the same format as the GET response (i.e., a source_products field that lists UUIDs of existing products).

推荐答案

您可以使用 PrimaryKeyRelatedField ,但必须编写自定义创建方法.

You can use PrimaryKeyRelatedField but you have to write custom create method.

class ProductSerializer(serializers.ModelSerializer):
    source_products = serializers.PrimaryKeyRelatedField(many=True, queryset=Products.objects.all())

    class Meta:
        model = Product
        fields = ('uuid', 'product_name', 'source_products', )

    def create(self, validated_data):
        source_products = validated_data.pop('source_products', [])
        product = Product.objects.create(**validated_data)
        for source in source_products:
            product.source_products.add(source)
        return product

您的数据将是这样

{
    "product_name": "dummy.fra",
    "source_products": [
        "17b021e7-3d6b-4d29-a80b-895d62710080"
    ],
    "uuid": "48c5a344-877e-4e3f-9a4b-2daa136b68fe"
}

这篇关于如何在Django Rest框架中使用Through模型制作可写的ManyToManyField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆