在模板中访问多个django模型for循环

时间:2016-06-29 13:15:24

标签: python django templates for-loop methods

我到处寻找解决这个特殊问题的方法,但是我找不到任何可以解答这个问题的方法。也许我的结构错了,但我在这里寻求帮助。

我的问题是我有一个填充Table Image

的表格

在此表中,前4列来自我的模型AdmissionTypes,后两列引用了我的模型Event中的一些方法。只要我在系统中只有一个事件,这就可以正常工作。如果我添加多个事件,则数字会合并。我无法找到一种方法来从一个方法中获取每个行中的所有项目。我知道我需要为它迭代的每个admission_type传递一个type_id,我只是不知道如何做到这一点,因为会返回多个type_ids。这是相关代码:

models.py

class Event(models.Model): 
    name = models.CharField(max_length = 100)
    date = models.DateField()
    time = models.TimeField()
    cash = models.DecimalField(decimal_places = 2, max_digits = 10,)

    def tickets(self):
        return self.tickets_set.all()

    # This one works, but I use this for an ajax request
    def admission_type_count(self, type_id):
        return self.tickets_set.all().filter(type=type_id).aggregate(Count('type__type')).values()[0]

class AdmissionType(models.Model):
    event = models.ForeignKey(Event)
    type = models.CharField(max_length=100)
    price = models.DecimalField(decimal_places=2, max_digits=10)

    def admission_type(self):
        return self.tickets_set.all()

    def admission_type_count(self):
        return self.admission_type().aggregate(Count('type')).values()[0]

    def admission_type_total_price(self):
    return self.admission_type().aggregate(Sum(F('type__price'))).values()[0]

views.py

def admission_types(request, event_id):
    tickets = Tickets.objects.filter(event=event_id)
    event = Event.objects.get(pk=event_id)
    types = event.admission_types().order_by('-price')
    expenses = event.expenses()
    total_revenue = event.tickets_total()
    cash = event.cash
    total_expenses = event.total_expenses()
    if total_revenue == None or total_expenses == None:
        cash_remaining = cash
    else:
        cash_remaining = ((total_revenue + cash) - total_expenses)
    for i in expenses:
        if i.percent > 0:
            i.cost = total_revenue * i.percent/100
            i.save()

    return render(request, "admissions.html", locals())

admission.html 在这个模板中,我试图弄清楚如何在仍然留在表格中的同时循环遍历所有相关数据。

{% for i in types %}
    <tr>
        <td>{{ i.type }}</td>
        <td>${{ i.price }}</td>
        <td class="add">
            <button data-typeid="{{ i.id }}" id="add-{{ i.id }}"></button>
        </td>
        <td class="del">
            <button data-typeid="{{ i.id }}" id="delete-{{ i.id }}"></button>
        </td>
        <td id="count-{{ i.id }}">{{ i.admission_type_count }}</td>
        {% if request.user.is_superuser %}
            <td id="total-{{ i.id }}">
                {% if i.admission_type_total_price == None %}
                    $0.00
                {% else %}
                    ${{ i.admission_type_total_price }}
                {% endif %}
            </td>
        {% endif %}
    </tr>
    {% endfor %}

感谢任何人提供的任何帮助。这让我疯了!

0 个答案:

没有答案