许多人通过模板中的关系来逆转

时间:2015-01-13 15:54:21

标签: django django-templates django-views

我想访问有关反向关系的数据,我想在一天内列出所有销售的清单,但我不知道做出反向关系的正确方法。

  1. 模板上有一些方法吗?
  2. 最好在View上做一些自定义过滤器???
  3. 模特

    class Product(models.Model):
        name = models.CharField(null=True, max_length=30, )
        price = models.IntegerField(default=0)
        description = models.CharField(null=True, max_length=100, )
    
    class Order(models.Model):
        date = models.DateTimeField(auto_now_add=True, null=True)
        table = models.IntegerField(null=False, max_length=2, )
        waiter = models.ForeignKey(User, null=True,default=None)
        products = models.ManyToManyField(Product,through='OrderProduct')
        paid = models.BooleanField(default=False)
        total = models.IntegerField(default=0,editable=False,null=True)
    
        @cached_property
        def total(self):
            x = 0
            for product in self.products.all():
                relationship_queryset = OrderProduct.objects.filter(order=self, product=product)
                for p in relationship_queryset.all():
                     x +=  p.total_products
            return x
    
    class OrderProduct(models.Model):
        order = models.ForeignKey(Order)
        product = models.ForeignKey(Product)
        products_quantity = models.IntegerField(max_length=2)
        products_total = models.IntegerField(default=0,editable=False)
    
        def save(self, *args, **kwargs):
            self.products_total = (self.product.price * self.products_quantity)
            super(OrderProduct, self).save(*args, **kwargs)
    

    视图

    def sales(request):
      today = datetime.utcnow()
      today_sales = m.Order.objects.filter(date=today).all()
      return render_to_response('pages/sales.html',{'request':request,'sales':today_sales})
    

    模板

    {% for sale in sales %}
        <ul>{{ sale.date }}|{{ sale.paid }}|{{ sale.total }}</ul>
    
      !! Here i wanna put the products from the current sale !!
      {% for product in sales.products %}
        {{ product.name }}|{{ product.price }}|{{ product.products_quantity }}|{{ product.products_total }}
      {% endfor %}
    {% endfor %}
    

1 个答案:

答案 0 :(得分:1)

使用backward relationship

{% for order_product in sale.orderproduct_set.all %}
    {{ order_product.product.name }}|{{ order_product.product.price }}|{{ order_product.products_quantity }}|{{ order_product.products_total }}
{% endfor %}