通过合并两个模型来创建报告表

时间:2019-07-01 19:55:24

标签: django python-3.x django-templates

我有两个模型,我想结合这两个模型并创建一个表,如下面的输出所示。请用视图和模板代码指导我。

class Question(models.Model):
    question = models.CharField(max_length=200)
    alias = models.CharField(max_length=25)

class Answer(models.Model)
    qst_id = models.ForeignKey(Question,on_delete=models.CASCADE)
    user_phone = models.CharField(max_length=200)
    user_response = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)

输入数据:(问题表)

qid  |  question   |   Alias 
==============================
1       Your name.?    Name 

2       Your Age.?     Age

3       Your Class?    Class 

数据:答案表

id   | qst_id  |   user_phone  | user_response
================================================
1      1           999999        jhony

2      2           999999        12 

3      3           999999        Second class

4      1           999988        Ramesh

2      2           999988        15 

3      3           999988        First class

输出:(预期)

S.No    | user_phone  | Name | Age | Class 
============================================
1         999999        jhony   12   second class

2         999988        ramesh  15   First class 

我的代码:

class ReportListlView(LoginRequiredMixin,ListView):
    model = Answers
    template_name  = 'web/test.html'


    def get_context_data(self, **kwargs):
        pk=self.kwargs.get('pk')
        context = super(ReportListlView, self).get_context_data(**kwargs)
        context['answers'] = Answers.objects.all()
        context['question'] = Question.objects.all()

        return context

temaplate / test.html

<div >
<table class='table table-condensed'>
<tr>
     <th>S.No</th>
     <th>Phone Number</th>
    {% for item in question %}
      <th>{{ item.alias  }}</th>
    {% endfor %}
    </tr>
    {% for item in answers %}
    <tr>
    {% ifchanged item.user_phone %}
        <td>{{ forloop.counter }}</td>
        <td>{{ item.user_phone }}</td>
    {% endifchanged %}`enter code here`
          <td>{{ item.user_response }}</td>
    {% ifchanged item.user_phone %}
    </tr>
    {% endifchanged %}`enter code here
    {% endfor %}
  </table>
</div></article>

0 个答案:

没有答案