我想以 CSV 格式导出我的数据库。到目前为止,“我的”代码仅适用于一张桌子......
这是我的模型:
class ActsIdsModel(models.Model):
year = models.IntegerField(max_length=4, blank=False, null=False)
...lots of other fields...
class NationRespModel(models.Model):
nationResp=models.CharField(max_length=2, unique=True)
class EUGroupRespModel(models.Model):
euGroupResp=models.CharField(max_length=50, unique=True)
class RespProposModel(models.Model):
respPropos=models.CharField(max_length=50, unique=True)
nationResp = models.ForeignKey('NationRespModel', blank=True, null=True, default=None)
euGroupResp = models.ForeignKey('EUGroupRespModel', blank=True, null=True, default=None)
class GvtCompoModel(models.Model):
gvtCompo= models.CharField(max_length=1000, blank=False, null=False)
class ActsInfoModel(models.Model):
#id of the act
actId = models.OneToOneField(ActsIdsModel, primary_key=True)
respProposId1=models.ForeignKey('RespProposModel', related_name='respProposId1', blank=True, null=True, default=None)
respProposId2=models.ForeignKey('RespProposModel', related_name='respProposId2', blank=True, null=True, default=None)
respProposId3=models.ForeignKey('RespProposModel', related_name='respProposId3', blank=True, null=True, default=None)
gvtCompo= models.ManyToManyField(GvtCompoModel)
...lots of other fields...
我使用下面的代码从一个模型中导出所有数据:
import csv
from django.db.models.loading import get_model
def dump(qs, outfile_path):
model = qs.model
writer = csv.writer(open(outfile_path, 'w'))
headers = []
for field in model._meta.fields:
headers.append(field.name)
writer.writerow(headers)
for obj in qs:
row = []
for field in headers:
val = getattr(obj, field)
if callable(val):
val = val()
if type(val) == unicode:
val = val.encode("utf-8")
row.append(val)
writer.writerow(row)
(来源: http: //palewi.re/posts/2009/03/03/django-recipe-dump-your-queryset-out-as-a-csv-file/)
以下是我获取所有模型的方法(主模型 + 链接到主模型的模型):
db_queryset=ActsInfoModel.objects.select_related().all().prefetch_related('gvtCompo')
我的问题是:如何将此查询集链接到转储函数?到目前为止,我只从 ActsInfoModel 获取数据......
我应该使用下面的代码,用于显示和检查所有数据:
for act in db_queryset.iterator():
#ActsIdsModel
for field in act.actId.__class__._meta.fields:
print field.name, getattr(act.actId, field.name)
#ActsInformationModel
for field in act.__class__._meta.fields:
print field.name, getattr(act, field.name)
#RespProposModel (3 respPropos)
for index in xrange(1,4):
index=str(index)
try:
print getattr(act, "respProposId"+index).respPropos
print getattr(act, "respProposId"+index).nationResp.nationResp
print getattr(act, "respProposId"+index).euGroupResp.euGroupResp
except Exception, e:
print "exception", e
#NPModel (gvtCompo)
for gvtCompo in act.gvtCompo.all():
print "gvtCompo", gvtCompo.gvtCompo