如何在Django模板中显示中间m2m模型的值

时间:2015-03-20 14:58:29

标签: python django templates views m2m

我正在使用模板标签迭代模板中的查询集,以显示现有数据库条目的数据(即客户订单中每个产品的产品详细信息)。但是,我想向用户显示订单中每个产品的产品和订单模型之间的中间m2m模型中的一些值(即数量和价格)。

我的方法是在视图中创建查询集,并将它们通过上下文传递到模板中,但我似乎无法调用'模板上的值使用中间m2m数据的模板标签。也许我的上下文传递了错误的查询集,或者我的方法是错误的。

我的代码如下,感谢您提供的任何帮助:

Models.py代码段

class Product(models.Model):
    article_number = models.ForeignKey('Article_number')
    color = models.ForeignKey('Color')
    size = models.ForeignKey('Size')
    barcode = models.ForeignKey('Barcode')
    product_name = models.ForeignKey('Product_name')
    brand = models.ForeignKey('Brand')
    category = models.ForeignKey('Category')
    manufacturer = models.ForeignKey('Manufacturer')
    cost_currency = models.ForeignKey('Cost_Currency', null=True, blank=True)
    cost_price = models.DecimalField(decimal_places=2, max_digits=10)
    selling_currency = models.ForeignKey('Selling_Currency', null=True, blank=True)
    selling_price = models.DecimalField(decimal_places=2, max_digits=10)
    description = models.TextField(null=True, blank=True)
    created_on = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated_on = models.DateTimeField(auto_now_add=False, auto_now=True)
    last_edited_by = models.ForeignKey(User, null=True, blank=True)
    active = models.BooleanField(default=True)

    class Meta:
        unique_together = (("article_number", "size", "color"))
        verbose_name = "Product"
        verbose_name_plural = "*Products*"

    def __unicode__(self):
        return str(self.article_number) + "-" + str(self.color) + "-" + str(self.size)


class Order(models.Model):
    order_status = models.ForeignKey('OrderStatus')
    products = models.ManyToManyField(Product, through='OrderProductDetails', through_fields=('order','product'), null=True, blank=True)
    counter = models.ForeignKey(Counter, null=True, blank=True)
    order_type = models.ForeignKey('OrderType')
    order_remarks = models.CharField(max_length=1000, null=True, blank=True)
    order_date = models.DateTimeField(auto_now_add=True, auto_now=False)
    ordered_by = models.ForeignKey(User, null=True, blank=True)
    promo = models.ForeignKey('promo.Promo', verbose_name="Order for which Promotion (if applicable)", null=True, blank=True)
    delivery_date = models.DateField(blank=True, null=True)
    delivery_remarks = models.CharField(max_length=1000, null=True, blank=True)
    updated_on = models.DateTimeField(auto_now_add=False, auto_now=True)

    class Meta:
        verbose_name = "Order"
        verbose_name_plural = "*Orders*"

    def __unicode__(self):
        return str(self.id)


class OrderProductDetails(models.Model):
    order = models.ForeignKey('Order')
    product = models.ForeignKey('products.Product')
    quantity = models.PositiveIntegerField()
    selling_price = models.DecimalField(decimal_places=2, max_digits=10)
    order_product_remarks = models.ForeignKey('OrderProductRemarks',blank=True, null=True)

    class Meta:
        verbose_name_plural = "Order - Product Details"
        verbose_name = "Order - Product Details"

    def __unicode__(self):
        return str(self.id)

Views.py Snippet

from django.shortcuts import render, Http404, HttpResponseRedirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib import messages
from django.forms.models import modelformset_factory
from orders.models import Order, OrderStatus, OrderProductDetails

@login_required(login_url='/admin/login/?next=/')
def warehouseOrder(request, id):
    try:
        order = Order.objects.get(id=id)
        products = order.products.all()

        orderDetails = OrderProductDetails.objects.filter(order__id=id)

        context = {'order': order, 'products': products, 'orderDetails': orderDetails}
        template = 'warehouse_order.html'
        return render(request, template, context)
    except:
        raise Http404

Template.html代码段

        <table class="table table-striped table-bordered">
            <tr>
                <th class="bottom-align-th">#</th>
                <th class="bottom-align-th">Article No.</th>
                <th class="bottom-align-th">Color</th>
                <th class="bottom-align-th">Size</th>
                <th class="bottom-align-th">Quantity</th>
                <th class="bottom-align-th">Unit Price</th>
                <th class="bottom-align-th">Remarks</th>
                <th class="bottom-align-th">Barcode No.</th>
                <th class="bottom-align-th">Packed</th>
            </tr>
           {% for product in products %}
            <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ product.article_number }}</td>
                <td>{{ product.color }}</td>
                <td>{{ product.size }}</td>
                <td>{{ orderDetails.quantity }}</td>
                <td>{{ orderDetails.selling_price }}</td>
                <td>{{ orderDetails.order_product_remarks }}</td>
                <td>{{ product.barcode }}</td>
                <td><input type="checkbox" id="large-checkbox"></td>
            </tr>
            {% endfor %}
        </table>

顺便说一句,在这里使用Django 1.7.2。

1 个答案:

答案 0 :(得分:0)

你正在绕过错误的东西。每个Order都有多个OrderProductDetails相关对象,每个对象只有一个Product。但是你在循环所有产品。尝试类似:

{% for detail in orderDetails %}
    <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ detail.product.article_number }}</td>
        <td>{{ detail.product.color }}</td>
        <td>{{ detail.product.size }}</td>
        <td>{{ detail.quantity }}</td>
        <td>{{ detail.selling_price }}</td>
        <td>{{ detail.order_product_remarks }}</td>
        <td>{{ detail.product.barcode }}</td>
        <td><input type="checkbox" id="large-checkbox"></td>
    </tr>
{% endfor %}