如何修复在 django Rest 框架中序列化 ManyToManyField 时获取 None 值

发布于 2025-01-14 21:47:12 字数 1502 浏览 3 评论 0原文

很抱歉问一个重复的问题,这个问题已经被问过很多次了。我看过很多关于这个话题的答案。但我无法重现我的问题的解决方案。 基本上我想序列化报价模型中的字段名称合作伙伴

class Quote(models.Model):
     #...
     partner = models.ManyToManyField(
        Partner, blank=True, related_name='quote_partners')

,这是帐户应用程序中的合作伙伴模型

class Partner(models.Model):
    id = models.UUIDField(primary_key=True,
                          unique=True,
                          default=uuid.uuid4,
                          editable=False)
    name = models.CharField(max_length=100, blank=True, null=True)
    group = models.OneToOneField(
        Group, on_delete=models.DO_NOTHING, blank=True, null=True)

    def __str__(self):
        return self.name

这就是序列化程序的外观

class QuoteListSerializer(serializers.Serializer):
    """ For the List views """
    #...
    id = serializers.UUIDField(read_only=True)
    partner = serializers.CharField(read_only=True)

我正确获取所有其他字段,但不是合作伙伴字段。 最终结果如下所示:

{           
            "id": "cbf64980-1637-4d0d-ad1f-4eb6421df5a1",
            "partner": "accounts.Partner.None", 
        },

但是我可以看到管理页面中此特定条目的合作伙伴字段已填充,但未显示在序列化数据中。 在合作伙伴模型中

在此处输入图像描述

在引用中

[“输入图片此处描述"][2

任何人都知道为什么会发生这种情况以及如何解决此问题。

Sorry to ask a repetitive question which is already have been asked a lot of times. I have seen alot of answers on this topic. But I can't reproduce the solution of my problem.
Basically I want to serialize a field name partner which is in quote model

class Quote(models.Model):
     #...
     partner = models.ManyToManyField(
        Partner, blank=True, related_name='quote_partners')

and this is the Partner models in the accounts app

class Partner(models.Model):
    id = models.UUIDField(primary_key=True,
                          unique=True,
                          default=uuid.uuid4,
                          editable=False)
    name = models.CharField(max_length=100, blank=True, null=True)
    group = models.OneToOneField(
        Group, on_delete=models.DO_NOTHING, blank=True, null=True)

    def __str__(self):
        return self.name

And this is how the serializer looks

class QuoteListSerializer(serializers.Serializer):
    """ For the List views """
    #...
    id = serializers.UUIDField(read_only=True)
    partner = serializers.CharField(read_only=True)

I'm getting all other fields properly but not the partner field.
This is the end results looks like :

{           
            "id": "cbf64980-1637-4d0d-ad1f-4eb6421df5a1",
            "partner": "accounts.Partner.None", 
        },

However I can see the partners field is filled for this specific entry in the admin page but not showing in the serialized data.
In the Partner Model

enter image description here

In the Quote

[enter image description here][2

Anybody knows why this is happening and how to fix this issue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光暖心i 2025-01-21 21:47:12

如果您已经拥有相关字段的各个对象,并且正如您在评论中提到的,您想要 UUID(也是合作伙伴模型的主键),那么可以使用 PrimaryKeyRelatedField

PrimaryKeyRelatedField 可用于表示
使用其主键的关系。 更多信息

修改您的QuoteListSerializer
from

partner = serializers.CharField(read_only=True)

partner = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

这将返回链接到您的 Quote 模型的特定对象的 UUID 集。

"partner": [
                "115f1fa8-1cb2-4d49-962d-8c25e8b40240" # UUID of the linked partner
            ],

如果你想返回字符串值那么你应该使用StringRelatedField

StringRelatedField 可用于表示对象的目标
使用其 __str__ 方法建立关系。 更多信息

这将返回名称合作伙伴对象的 ,因为您已在合作伙伴模型中将其设置为 return self.name

因此您可以获得以下格式,

"partner": [
                "Company A" # name of the linked partner
            ],

If you already have the individual objects of the related fields, and as you mentioned in the comments you want the UUID which is a primary key of the Partner model as well, So can use the PrimaryKeyRelatedField.

PrimaryKeyRelatedField may be used to represent the target of the
relationship using its primary key. More Info

Modify your QuoteListSerializer
from

partner = serializers.CharField(read_only=True)

to

partner = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

This will return the set of UUID of those specific objects that are linked to your Quote model.

"partner": [
                "115f1fa8-1cb2-4d49-962d-8c25e8b40240" # UUID of the linked partner
            ],

If you want to return the string value then u should use StringRelatedField

StringRelatedField may be used to represent the target of the
relationship using its __str__ method. More Info,

This will return the name of the Partner Objects as you have set this in the Partner model to return self.name

So you can obtain as the following formate,

"partner": [
                "Company A" # name of the linked partner
            ],
绮烟 2025-01-21 21:47:12

您还必须创建 Partner 类的序列化器类。在 QuoteListSerializer 中,您调用此合作伙伴序列化程序。然后,合作伙伴序列化程序将嵌套在 json 中。

class QuoteSerializer(serializers.ModelSerializer):

    partner = PartnerSerializer(read_only=True)

    class Meta:
        model = Quote
        fields = __All__ you can exclude fields

You have to make also a serializer class of the Partner class. In the QuoteListSerializer you call this partner serializer.The partner serializer will then be nested in the json.

class QuoteSerializer(serializers.ModelSerializer):

    partner = PartnerSerializer(read_only=True)

    class Meta:
        model = Quote
        fields = __All__ you can exclude fields
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文