【问题标题】:How to serialize models in Django?如何在 Django 中序列化模型?
【发布时间】:2014-03-19 18:23:38
【问题描述】:

我有一个非常简单而明显的问题,我正在尝试搜索一段时间。

我有一个模型Picture,它有created_byProvinceCity 等外键。

我想要的是将所有模型字段序列化为json

模型.py:

class Picture(models.Model):
    name = models.TextField("Title", max_length=10000, null=True, blank=True)
    meta_data = models.TextField("meta_data", null=True, blank=True)
    created_by = models.ForeignKey(User, related_name="created_by")
    city = models.ForeignKey(City, null=True, blank=True)
    pro = models.ForeignKey(Province, verbose_name="Province")


class Province(models.Model):
    name = models.CharField(max_length=50)
    pi_meta_data = models.TextField(null=True, blank=True)
    intro = models.CharField(max_length=1000, null=True, blank=True)
    description = models.TextField(max_length=10000, null=True, blank=True)


class City(models.Model):
    name = models.CharField(max_length=50)
    pi_meta_data = models.TextField(null=True, blank=True)
    intro = models.CharField(max_length=1000, null=True, blank=True)
    description = models.TextField(max_length=10000, null=True, blank=True)

【问题讨论】:

  • 您是否尝试将列名传递给queryset.values()?我知道“神奇地生成”的想法很有吸引力,但在现实世界中并不是很有用。我正在使用生成简单字典或字典列表的特定 DTO 工厂;例如。 def pictures_list_dto_factory(picture_queryset) 或/和def picture_details_dto_factory(picture_instance)。您可以轻松地序列化这些工厂的输出,例如使用json.dumps。如果这不是您的解决方案,请提供有关您的用例的更多详细信息。

标签: python json django api serialization


【解决方案1】:

您可以轻松使用Django Rest Frameworkserialize 模型。

您的模型序列化程序将是:

class PicturesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Picture
        # Only including fields in this case to explicitly show that 
        # every field in the Pictures model is serialized. In the rest of 
        # the Serializes fields will be left out for brevity.
        fields = ("name", "meta_data", "created_by", "city", "pro")

class ProvinceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Province


class CitySerializer(serializers.ModelSerializer):

    class Meta:
        model = City

就是这样。说真的。

一切都很好地为您打包到 json 中,即使您更改了您的模型。

但是使用序列化数据有多容易?使用这些序列化模型的简单视图是:

class PicturesList(APIView):
    """
    List all Pictures, or create a new Picture.
    """
    def get(self, request, format=None):
        pictures = Pictures.objects.all()
        serializer = PicturesSerializer(pictures, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = PicturesSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

文档确实令人惊叹。他们有一个很酷的tutorial 来帮助您入门。他们甚至有一个甜蜜的browseable api,让您可以直观地浏览您的 api。

【讨论】:

  • 我真的很喜欢这个答案和代码的简洁性。但我的问题仍然存在。我想获取外键数据。比如图片 = pic.name, pic.created_by.name, pic.created_by.id, pic.created_by.email。
  • @user570826 Picture中的外键字段也在PictureSerializer中被序列化了!你想要其他模型中的反向关系吗?
  • @user570826 即。 PictureSerializer中序列化的字段有name、meta_data、created_by、city、pro。
【解决方案2】:

有一个“Django Full Serialization”模块,它是 wadofstuff 的一部分,可以序列化相关对象等。这个答案https://stackoverflow.com/a/3753769/187729 有更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2018-11-21
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多