我正在将 django (v1.1) 项目从 mysql 移动到 postgresql (有趣!),目前我正在传输所有数据。我尝试使用 manage.py dumpdata 选项,但我们使用的服务器相当旧并且需要很长时间(它似乎想将所有内容加载到内存中)。我想出了一个小脚本来处理每个应用程序,然后处理它下面的每个模型,简化版本如下所示:
def dumpJson(model, outfile):
try:
data = serializers.serialize("json", model.objects.all(),indent=4)
except model.DoesNotExist:
print model.__name__ , "Does not Exist (not Object)"
except ObjectDoesNotExist:
print model.__name__ , "Issue with the data, not sure what...."
data = serializers.serialize("json", model.objects.all(),indent=4)
data = data.decode("unicode_escape").encode("utf8")
out = open(outfile, "w")
out.write(data)
out.close()
def main():
for app in get_apps():
for model in get_models(app):
print " -- Dumping:", model.__name__
outfile = "json_dumps/" + model.__name__ + ".json"
dumpJson(model, outfile)
但是,如果我删除 try catch 语句,我会收到以下错误:\
-- Dumping: Institution
Traceback (most recent call last):
...(nasty stacktrace)....
unity.trip.models.DoesNotExist: USNWRData matching query does not exist.
我的模型定义如下:
class USNWRData(models.Model):
rank = models.PositiveIntegerField(blank=True, null=False)
name = models.CharField(max_length=255, blank=True, null=False)
state = models.CharField(max_length=10, blank=True, null=False)
public = models.BooleanField(blank=True, null=False)
type = models.ForeignKey(USNWRType)
class Institution(models.Model):
name = models.CharField(max_length=200)
parent_institution = models.ForeignKey('self', blank=True, null=True)
location = models.ForeignKey(Location, blank=True, null=True,related_name='old_location')
type = models.ForeignKey(InstitutionType, blank=True, null=False )
usnwr = models.ForeignKey(USNWRData, blank=True, null=True)
locationnrm = models.ForeignKey(LocationNrm, blank=False, null=True)
据我了解,此错误的原因是某种数据不匹配或缺少外键。鉴于上述模型,问题似乎是什么?我有点麻烦,原作者早就不在了。任何帮助将非常感激!
编辑:全栈交易是:
-- Dumping: Institution
Traceback (most recent call last):
File "custom_dump.py", line 38, in <module>
main()
File "custom_dump.py", line 34, in main
dumpJson(model, outfile)
File "custom_dump.py", line 16, in dumpJson
data = serializers.serialize("json", model.objects.all(),indent=4)
File "/usr/local/lib64/python2.5/site-packages/django/core/serializers/__init__.py", line 91, in serialize
s.serialize(queryset, **options)
File "/usr/local/lib64/python2.5/site-packages/django/core/serializers/base.py", line 48, in serialize
self.handle_fk_field(obj, field)
File "/usr/local/lib64/python2.5/site-packages/django/core/serializers/python.py", line 48, in handle_fk_field
related = getattr(obj, field.name)
File "/usr/local/lib64/python2.5/site-packages/django/db/models/fields/related.py", line 315, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "/usr/local/lib64/python2.5/site-packages/django/db/models/query.py", line 349, in get % self.model._meta.object_name)
unity.trip.models.DoesNotExist: USNWRData matching query does not exist.