2
如何在json文件中寫入我的數據?這是我的嘗試:如何在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/
我寧願後面的例子。當你不需要它們時引入大量變量(data,data2,data3?)是一個壞習慣。幾乎與具有非常通用的變量名稱(如「數據」)一樣糟糕 – baloo 2013-02-13 17:19:20
@baloo:我同意;但是在幫助某個人時,我希望儘可能重新使用他們的代碼,以便它可以被識別,並且他們可以更容易地看到丟失的東西。 :-) – 2013-02-13 17:20:19
絕對,只是指出:) – baloo 2013-02-13 17:33:36