我的Django应用程序中有可用的CSV导出功能。
它导出所有字段,但不显示模型选择字段的详细版本或人类可读版本。
我知道模板和视图的get_field_display选项,但是基于此函数中getattr的使用,我不知道将代码添加到何处。参见下面的代码
writer = csv.writer(response)
field_names = [f.name for f in model._meta.fields]
for instance in queryset:
writer.writerow([unicode(getattr(instance, f)).encode('utf-8') for f in field_names])
return response
在哪里可以注入一些代码以导出完整版本的模型选择。
谢谢
答案 0 :(得分:1)
使用model_obj.get_FOO_display()
方法
示例:
class Foo(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
和外壳响应
In [2]: foo_obj = Foo.objects.first()
In [3]: foo_obj.get_gender_display()
Out[3]: 'Male'
In [4]: foo_obj.__dict__
Out[4]:
{'_state': ,
'id': 1,
'gender': 'M'}
更新
在列表理解语句中使用if...else
语句。
writer.writerow([unicode(getattr(instance, f)).encode('utf-8') if f != 'FOO' else unicode(getattr(instance, 'get_FOO_display')()).encode('utf-8') for f in field_names])
示例
In [8]: class MySample(object):
...: f_name = 'foo'
...: l_name = 'bar'
...:
...: def full_name(self):
...: return self.f_name + " " + self.l_name
...:
In [9]: class_obj = MySample()
In [10]: getattr(class_obj,'f_name')
Out[10]: 'foo'
In [11]: getattr(class_obj,'l_name')
Out[11]: 'bar'
In [12]: getattr(class_obj,'full_name')()
Out[12]: 'foo bar'
答案 1 :(得分:0)
body_rows = []
for entry in Entry.objects.all():
row = []
for key in header_data:
if key == 'district':
row.append(entry.get_district_display())
elif key == 'local_body':
row.append(entry.get_local_body_display())
else:
row.append(getattr(entry, key))
body_rows.append(row)