2016-09-20 46 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