如何在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() )
实际上,您并不是在编写数据,而是转换为JSON。对打开的文件调用
.write()
:只打开
file.json
一次;每次用'w'
模式打开它进行写入时,它都会首先被擦除。在或者,get a reference to the serializer并告诉它直接写入打开的文件:
^{pr2}$哪个更有效。在
相关问题 更多 >
编程相关推荐