Django从SQL DB下载CSV并渲染模板

时间:2015-01-21 22:29:41

标签: python django postgresql csv

这是一个满载的问题...

所以我有一个带有PostgreSQL DB的Django应用程序。我想提供一个选项,用户可以从DB下载一组特定的表作为csv文件。

├── app
│   ├── admin.py
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── templates
│   │   └── anthropometrics
│   │       ├── form.html
│   │       └── index.html
│   ├── urls.py
│   └── views.py

所以这是我的一个示例应用程序。我想在models.py(作为CSV)中导出几乎所有内容。但是,当我这样做时,我想重新回到原始页面。

所以我将拥有我的index.html:

<div class="container">
  <nav class="navbar navbar-default" role="navigation">
      <div class="container-fluid">
          {% if user.is_authenticated %}
              <a href="{% url 'app:form' %}"><button type="button" class="btn btn-default navbar-btn">Enter Data</button></a>
              <a href="{% url 'app:view' %}"><button type="button" class="btn btn-default navbar-btn">View Data</button></a>
              <a href="{% url 'app:download' %}"><button type="button" class="btn btn-default navbar-btn">GET Data</button></a>
          {% endif %}
      </div>
  </nav>

{% block next %}{% endblock %}

编辑:

应用按钮会在views.py

中呈现此视图
def get_model_fields(model):
    return model._meta.fields
def download(request):
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))+"/anthropometrics"
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=data.csv'
    writer = csv.writer(response)
    for model in [base,question1,question2,question3,question4]:
        name = model.__name__
        # Write headers to CSV file
        fields = get_model_fields(model)
        if fields:
            headers = fields
        else:
            headers = []
            for field in model._meta.fields:
                headers.append(field.name)
        writer.writerow(headers)
        # Write data to CSV file
        for obj in model.objects.all():
            row = []
            for field in headers:
                if field in headers:
                    val = getattr(obj, field.name)
                    if callable(val):
                        val = val()
                    row.append(val)
            writer.writerow(row)
        # Return CSV file to browser as download
    return response

上面的示例代码就像只提供普通文本文件一样。我想,使用csv

中的import csv可能会接近这一点

任何帮助?

这是我的models.py:

class base(models.Model):
    mothers_id = models.IntegerField(primary_key=True)
    date = models.DateField()
    data_collector = models.CharField(max_length=50)

class question1(models.Model):
    question1_base = models.OneToOneField(base, primary_key=True)
    question1_1a_in_cm  = models.IntegerField(default=False)
    question1_1a_in_in  = models.IntegerField(default=False)
    question1_1b_in_kg  = models.IntegerField(default=False)
    question1_1b_in_lbs = models.IntegerField(default=False)
class question2(models.Model):
    question2_base = models.OneToOneField(base, primary_key=True)
    question2_2a = models.CharField(max_length=2, choices=get_choices(2, 'YES', 'NO'))
    question2_2a_explanation = models.CharField(max_length=100, null=True, blank=True)
    question2_2b = models.CharField(max_length=2, choices=get_choices(2, 'YES', 'NO'))
    question2_2b_explanation = models.CharField(max_length=100, null=True, blank=True)
class question3(models.Model):
    question3_base = models.OneToOneField(base, primary_key=True)
    question3_3a_in_cm  = models.IntegerField(default=False)
    question3_3a_in_in  = models.IntegerField(default=False)
    question3_3b_in_kg  = models.IntegerField(default=False)
    question3_3b_in_lbs = models.IntegerField(default=False)
class question4(models.Model):
    question4_base = models.OneToOneField(base, primary_key=True)
    question4_4a_in_cm = models.IntegerField(default=False)
    question4_4a_in_in = models.IntegerField(default=False)
    question4_4a_not_known = models.CharField(max_length=2, choices=get_choices(1, 'YES'), null=True, blank=True)
    question4_4b_in_kg = models.IntegerField(default=False)
    question4_4b_in_lbs = models.IntegerField(default=False)
    question4_4b_not_known = models.CharField(max_length=2, choices=get_choices(1, 'YES'), null=True, blank=True)
    question4_4c = models.CharField(max_length=2, choices=get_choices(3, 'Hospital/Clinic Health Card', 'Mother', 'Other'))
    question4_4d = models.CharField(max_length=2, choices=get_choices(2, 'YES', 'NO'))
    question4_4d_explanation = models.CharField(max_length=100, null=True, blank=True)
    question4_4e = models.CharField(max_length=2, choices=get_choices(2, 'YES', 'NO'))
    question4_4e_explanation = models.CharField(max_length=100, null=True, blank=True)

我非常关注,我无法弄清楚如何将models.py(SQL中的表)中的多个类添加到同一个csv文件中

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。我只是在views.py中稍微使用了代码。最新的EDIT具有正确的代码