【问题标题】:Django rest_framework serializer with inner relationship具有内部关系的 Django rest_framework 序列化程序
【发布时间】:2014-09-30 15:33:46
【问题描述】:

这是我的 models.py 的一部分:

class Discount(models.Model):
    discount_id = models.AutoField(primary_key=True)
    discount_category = models.ManyToManyField(Category)
    discount_store = models.ManyToManyField(Store)
    ...

class Store(models.Model):
    store_id = models.AutoField(primary_key=True)
    store_company =models.ForeignKey('Company')
    store_city = models.ForeignKey('City', to_field='city_name')
    ....

这是我的serializer.py的一部分:

class StoreSerializer(serializers.ModelSerializer):
class Meta:
    model = Store
    fields = ('store_location', 'store_city', 'store_name', 'store_address')


class DiscountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Discount
        fields = ('discount_description', 'discount_start', 'discount_end', discount_title', 'discount_category', 'discount_store')

当我为折扣创建 JSON 时,我得到了这个 JSON。

[{
    "discount_description": "Description here.",
    "discount_start": "2014-08-07T14:35:13Z",
    "discount_end": "2014-08-30T14:35:15Z",
    "discount_title": "Lorem İpsum",
    "discount_category": [
        3
    ],
    "discount_store": [
        1
    ]
}]

但我想在“discount_store”中查看商店详情。我为此尝试了很多关系。但我总是得到这个 JSON。

【问题讨论】:

  • 在我如上重命名表定义中的外键列名后,它开始回升。我认为最好覆盖默认的外键列名并给出类似 store_city 的内容(在这种情况下,迁移后它将是数据库中的 store_city_id),可以在序列化程序类中提及。

标签: python json django serialization django-rest-framework


【解决方案1】:

您是否尝试将选项 depth 添加到 Meta 类?可能是这样的:

class DiscountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Discount
        fields = ('discount_description', 'discount_start', 'discount_end', 'discount_title', 'discount_category', 'discount_store')
        depth = 1

【讨论】:

  • 非常感谢。有用。我尝试了序列化程序中的每一个关系。但解决方案是深度选项。我不明白为什么。顺便说一句,你能添加“discount_title”的单引号开头吗?
  • 我在discount title 之前添加了缺少的单引号。你是对的,我在复制别人的代码时应该更加小心。选项depth在DRF的官方文档中有说明。如果模型结构更深并且需要显示更多信息,也可以使用除 1 之外的其他数字。
  • 在您发表第一条评论后,我阅读了 rest_framework 文档。不是我明白了。如果我在 Store 中有另一个关系,我可以使用 depth=2。感谢您的快速响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 2018-08-31
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
  • 2016-12-18
  • 2017-10-30
相关资源
最近更新 更多