2016-09-20 2 views
0

私はユーザーが1つのアイテムを選択して数量を選択できるオーダーフォームを持っています。価格は注文量によって異なります。たとえば、< 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ハックがintにchoice_valueに変換します。http://zurb.com/forrst/posts/Compare_string_and_integer_in_Django_templates-0AzをCF)

関連する問題