简体   繁体   English

压缩并下载Django Rest Framework生成的json文件

[英]zip and download Django Rest Framework generated json file

Let's suppose that my django rest framework app is returning this json for this url (where 4 is the pk of a model): http:mydomain.com/model_number/4/?format=json 假设我的django rest框架应用正在为此URL返回此json(其中4是模型的pk): http:mydomain.com/model_number/4/?format=json

[
    {
        "id": 96, 
        "title": "title 1",
        "picture": "static/uploads/pic1.jpg"
    },
    {
        "id": 97, 
        "title": "title 2",
        "picture": "static/uploads/pic2.jpg"
    },
    {
        "id": 98, 
        "title": "title 3",
        "picture": "static/uploads/pic3.jpg"
    }
]

I want to create and download a zip with a json file which has the content explained above (generated by django rest framework), and a folder with pic1 , pic2 and pic3 . 我想创建并下载一个ZIP与具有上述内容(由Django的REST框架生成),以及与文件夹解释JSON文件pic1pic2pic3

I'm able to download a zip with a folder containing those pictures, but I don't know how to include the json file. 我可以下载包含这些图片的文件夹的zip,但是我不知道如何包含json文件。

I don't know if it is related with parsers : 我不知道它是否与解析器有关:

Any help would be appreciated 任何帮助,将不胜感激

Just construct an instance of your serializer with model instance as argument. 只需使用模型实例作为参数构造序列化器的实例。 Serializer object has property data . 序列化程序对象具有属性data

class YourModel(models.Model):
    ...

class YourModelSerializer(serializers.ModelSerializer):
    ...

your_json = YourModelSerializer(YourModel.objects.get(pk=5)).data

You also can use queryset with flag many=True : 您还可以将queryset与标志many=True

your_json = YourModelSerializer(YourModel.objects.all(), many=True).data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM