Django Rest Framework用默认的“through”序列化ManyToManyField

2024-05-13 07:52:22 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我是DRF新手,我可以用外键序列化表,但是当涉及多对多字段时,在本例中:

Package <> Package_product_atom <> Product_atom

我该怎么把它连载呢?到目前为止,我正在尝试的是:

class Product_atomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product_atom
        ready_only = True
        fields = ('id','title', 'title_override', 'price', 'price_override', 'description', 'description_override','image', 'image_override' ,'tags', 'product_alt', 'date_modified', 'date_created')

class PackageSerializer(serializers.ModelSerializer):
    atomics = Product_atomSerializer(many=True)
    class Meta:
        model = Package
        ready_only = True
        fields = ('id', 'title', 'price', 'discount', 'image', 'tags', 'atomics', 'date_modified', 'date_created')

我的模型是:

^{pr2}$

如果它是一个ForeignKey关系的话,那就可以了,但是我不能用ManyToManyField来运行它,我得到的错误是:

AttributeError: Got AttributeError when attempting to get a value for field atomics on serializer PackageSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Package instance. Original exception text was: 'Package' object has no attribute 'atomics'.

我以前在序列化一对多关系时遇到过这个错误,但是使用related_name修复了它。使用through设置一个自定义模型并为其添加一个相关的\u名称是否可以修复它?谢谢您!在


Tags: imagetruepackagedate序列化titleproductprice
1条回答
网友
1楼 · 发布于 2024-05-13 07:52:22

您是否尝试过将变量名“atomics”更改为“product峎atom”?在

根据您的包类,“product\u atom”没有相关的名称“atomics”。在

相关问题 更多 >