【问题标题】:Is there a way to retrieve the value of object instead of its ID?有没有办法检索对象的值而不是它的 ID?
【发布时间】:2020-02-14 19:30:57
【问题描述】:

在使用 django.core.serializers.serialize 时,有什么方法可以检索对象而不是 ID (pk)。

我有一个名为 MenuItem 的模型,其中包含与 MenuSubItem 相关的 ManyToManyField。

当我执行此代码时serializers.serialize('json', MenuItem.objects.all()) 我得到了

{'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**3**]}}

但我真正想要的是

{'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**objects or objects_attribute**]}}

或者如果有使用其他库的解决方法

【问题讨论】:

标签: python django django-models django-serializer


【解决方案1】:

可能,实际上在 API 中很常见的事情是在 docs 中有一篇关于它的文章,看看DRF serializer relations,这称为嵌套序列化,当你想序列化一个有另一个东西的东西时可序列化,DRF 学起来很有趣,YouTube 上还有 JustDjango,他正在解释使用 DRF 的一些基础知识

您的代码应该看起来像

class mySerializer(serializers.ModelSerializer):

    Meta:
        model = myModelThatIwantToNest
        fields = ['....']

class myOtherSerializer(serializers.ModeSerializer):
    myModelThatIwantToNest = mySerializer();
    Meta:
        model = myOtherModel
        fields = ['myModelThatIwantToNest', '...']

【讨论】:

    猜你喜欢
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2021-03-17
    • 1970-01-01
    • 2022-11-22
    • 2012-04-09
    • 2010-11-20
    相关资源
    最近更新 更多