Django:访问ManytoMany字段

时间:2018-06-19 13:08:26

标签: django

我目前面临以下挑战。作为我页面的访问者,您可以在不同事件之间进行选择。假设您单击了一个按钮,现在您进入事件页面的是id 1。您可以选择不同的票证。假设您选择了具有19%增值税的机票1(100美元)和具有19%+ 7%增值税的机票2(200美元)(包括食品)。现在单击“检出”,下一页将列出以下内容:

1张票1-总计:USD 100

1张票2-总计:USD 200

总额:300美元


增值税1(19%):57美元(19 + 38)

增值税2(7%):USD 14


小计:229美元

我现在正努力应对“多对多”领域。您将如何访问各个票证,从相应的ManytoMany字段中获取增值税,然后在模板末尾显示它们?我考虑过元组,字典等,但是我真的很难在这里找到最好的方法。您是否曾经遇到过类似的代码挑战?

class TicketTax(models.Model):
    event = models.ForeignKey(
        Event,
        on_delete=models.PROTECT,
        related_name='ticket_taxes'
    )
    name = models.CharField(max_length=100)
    percentage = models.DecimalField(
        max_digits=5,
        decimal_places=4
    )
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)


class Ticket(models.Model):
    event = models.ForeignKey(
        Event,
        on_delete=models.PROTECT,
        related_name='tickets'
    )
    ticket_tax = models.ManyToManyField(TicketTax, blank=True)
    price_gross = models.DecimalField(
        max_digits=25,
        decimal_places=2
    )
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    start_at = models.DateTimeField()
    end_at = models.DateTimeField()
    quantity = models.PositiveIntegerField()
    status = models.CharField(
        max_length=8,
        choices=TicketStatus.CHOICES
    )
    is_archived = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

更新1:

reserved_item = ReservedItem.objects.filter(order_reference=session_order_reference)
tax_dict = {}
        for i in reserved_item:
            ticket_subtotal = i.ticket.price_gross * i.quantity

            taxes_for_this_ticket = i.ticket.ticket_tax.all()
            for taxes in taxes_for_this_ticket:
                amount_of_taxes = ticket_subtotal * taxes.percentage
                tax_dict[taxes] = amount_of_taxes

更新2(解决方案):

views.py

d = {}
    for i in reserved_item:
        ticket_subtotal = i.ticket.price_gross * i.quantity

        taxes_for_this_ticket = i.ticket.ticket_tax.all()

        for taxes in taxes_for_this_ticket:
            amount_of_taxes = ticket_subtotal * taxes.percentage

            if taxes in d:
                d[taxes] += amount_of_taxes
            else:
                d[taxes] = amount_of_taxes

    for key, value in d.items():
        print(key.name, " Value: ", value)

模板-checkout.html:

{% for key, values in taxes.items %}
    <p>
        {{key.name}}<br>
        {{values}}
    </p>
{% endfor %}

enter image description here

1 个答案:

答案 0 :(得分:0)

假设票证是一个票证对象, taxes_for_this_ticket = ticket.ticket_tax.all()

应该为您工作