2

如何将我的数据写入 json 文件?这是我的尝试:

from django.test import TestCase
from django_dynamic_fixture import G
import content.factories
from django.core import serializers
from content.models import UserProfile, Delivery
from django.contrib.auth.models import User

class DeliveryTest(TestCase):
    def test_sample_data(self):
        for i in range(0,10):
            user = content.factories.UserFactory.create()
            print user
            for j in range(0, 50):
                delivery = content.factories.DeliveryFactory.create(user=user)
                print delivery

                with open("file.json", "w") as out:
                    data = serializers.serialize("json", User.objects.all() ) 

                with open("file.json", "w") as out:
                    data2 = serializers.serialize("json", Delivery.objects.all() )

输出(打印):http ://dpaste.com/hold/923339/

4

1 回答 1

8

您实际上并没有编写数据,只是转换为 JSON。调用.write()打开的文件:

with open("file.json", "w") as out:
    data = serializers.serialize("json", User.objects.all())
    out.write(data)
    data2 = serializers.serialize("json", Delivery.objects.all() )
    out.write(data)

只开放file.json 一次;每次打开它以使用该'w'模式写入时,它都会首先被擦除。

或者,获取对序列化程序的引用并告诉它直接写入打开的文件:

with open("file.json", "w") as out:
    json_serializer = serializers.get_serializer('json')()
    json_serializer.serialize(User.objects.all(), stream=out)
    json_serializer.serialize(Delivery.objects.all(), stream=out)

哪个更有效率。

于 2013-02-13T16:14:48.197 回答