Python 基于模型元数据的通用导出模块:为foreignKey而不是模型类返回一个整数(使用值列表)
我尝试实现一个基于元数据模型的通用导出模块 它的工作原理是,对于foreignKey,除了返回整数而不是模型类的值Python 基于模型元数据的通用导出模块:为foreignKey而不是模型类返回一个整数(使用值列表),python,django,Python,Django,我尝试实现一个基于元数据模型的通用导出模块 它的工作原理是,对于foreignKey,除了返回整数而不是模型类的值 # Patient (1, False, 'CI-S1-0001', 5, 'admin', datetime.datetime(2021, 5, 31, 7, 26, 20, 393305, tzinfo=<UTC>)) # Inclusion (1, False, 1, datetime.date(2021, 5, 23)) 我找到了一个解决方案,使用带有Quer
# Patient
(1, False, 'CI-S1-0001', 5, 'admin', datetime.datetime(2021, 5, 31, 7, 26, 20, 393305, tzinfo=<UTC>))
# Inclusion
(1, False, 1, datetime.date(2021, 5, 23))
我找到了一个解决方案,使用带有QuerySet的annotate字段返回相关模型的字段值
class Patient(models.Model):
...
ide = models.AutoField(primary_key=True)
ver = models.BooleanField("Fiche verrouillée", null=True, blank=True, default=False)
pat = models.CharField("Patient",max_length=11, unique=True, null=True, blank=True, error_messages={'unique':'Un patient avec ce code existe déjà'})
pat_sit = models.ForeignKey('parameters.Site',on_delete = models.CASCADE, related_name='patient_site', db_column='pat_sit')
...
class Meta:
db_table = 'crf_pat'
verbose_name_plural = 'Patients'
...
def __str__(self):
return f"{self.ide} - {self.pat}"
class Inclusion(models.Model):
...
pat = models.ForeignKey('Patient',on_delete = models.CASCADE, related_name='inclusion_patient', db_column='pat')
...
log = HistoricalRecords()
...
...
app_models = apps.get_app_config('ecrf').get_models()
for model in app_models:
columns = [str(field_name).split('.')[-1] for field_name in model._meta.concrete_fields]
results = model.objects.all().values_list(*columns)
q = Q()
if model._meta.model.__name__ == 'Patient':
for site in sites:
q = q | Q(pat__icontains=site)
else:
for site in sites: # sites is a list
q = q | Q(pat__pat__icontains=site)
for row in results.filter(q).values_list(*columns):
print(row)
row_num += 1
for col_num in range(len(row)):
print('row_num',row_num)
print('col_num',col_num)
print('row[col_num]',row[col_num])
ws.write(row_num, col_num, row[col_num], normal_style)