2016-09-20 53 views
0

我有一个订单,用户可以选择一个项目并选择一个数量。价格取决于订购的数量。例如,如果您订购< 100,则每件商品的价格为10美元,如果订购100-200美元,则每件商品的价格为7美元。在ModelChoicefield中选择反向外键

在模板中,我想在每个选项的表单下方显示定价信息。

这是我的模型:

class Product(models.Model): 
    name = models.TextField() 

class Price(models.Model): 
    """ 
     This lets us define rules such as: 
     When ordering <100 items, the price is $10 
     When ordering 100-200 items, the price is $7 
     When ordering 200-300 items, the price is $5 
     etc 
    """ 
    price = models.FloatField() 
    min_quantity = models.PositiveIntegerField() 
    max_quantity = models.PositiveIntegerField() 
    product = models.ForeignKey(Product) 

class Order(models.Model): 
    product = models.ForeignKey(Product, null=False, blank=False, default='') 
    quantity = models.IntegerField() 

我可以遍历窗体域和独立的查询集:

{% for choice in form.product.field.queryset %} 
    <h1>{{choice}} {{choice.price_set.all}}</h1> 
{% endfor %} 

{% for choice in form.product %} 
    <h1>{{ choice.tag }} {{ choice.choice_label }}</h1> 
{% endfor %} 

...但我不知道如何将循环结合起来,显示表单域下的价格。

本质上,我想从ModelChoicefield小部件中选择一个反向外键。我需要一次循环表单字段和查询集,或者从表单元素访问查询集中的元素。理想情况下,这是我想什么我的模板做:

{% for choice in form.product %} 
    <h1>{{ choice.tag }} {{ choice.choice_label }}</h1> 
    {% for price in choice.price_set.all %} 
     <h1>{{price}} etc...</h1> 
    {% endfor %} 
{% endfor %} 

当然我不是第一人,这个用例。什么是最好的方法来做到这一点?

编辑:根据要求,这是我的形式和我的看法。回顾一下,我想我应该提到我正在使用RadioSelect小部件。

形式:

class OrderForm(forms.ModelForm): 
    class Meta: 
     exclude = ['date_added'] 
     widgets = { 
      'mailer': forms.RadioSelect 
     } 
     model = Order 

查看:

def processOrder(request): 
    if request.method == 'POST': 
     orderForm = OrderForm(request.POST) 
     if orderForm.is_valid(): 
      orderObject = orderForm.save() 
      return render(request, TEMPLATE_PREFIX + "confirm.html", {"orderObject": orderObject}) 
     else: 
      return render(request, TEMPLATE_PREFIX + "register.html", { "form": orderForm }) 
    else: 
     return render(request, TEMPLATE_PREFIX + "register.html", { "form": OrderForm()}) 
+0

你可以发布你的表单代码(表格+查看)? – vmonteco

+0

完成。往上看。 – Travis

回答

0

对于使用期限(非)的完美主义者,此代码的工作,尽管效率低下。

{% for choice in form.product %} 
    {% for price_candidate in form.mailer.field.queryset %} 
     {% if price_candidate.id == choice.choice_value|add:0 %} 
      <h1>{{ choice.tag }} {{ choice.choice_label }}</h1> 
      {% for price in price_candidate.price_set.all %} 
       <h1>{{price}} etc...</h1> 
      {% endfor %} 
     {% endif %} 
    {% endfor %} 
{% endfor %} 

(该add:0黑客转换choice_value成一个int。CF http://zurb.com/forrst/posts/Compare_string_and_integer_in_Django_templates-0Az