我想導出CSV格式的數據庫。 到目前爲止,「我的」代碼適用於只有一個表...導出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
我可以用這個導出鏈接到主一個ActsInfoModel的所有型號?我讀到「如果你正在出口所有關於一個模型的數據」...... – rom