2016-12-30 5 views
1

私はcredit_facilitiesという辞書を持っていますが、ここで私はクレジットファシリティIDを口頭でreprsentationにマップします。djangoテンプレートエンジンで辞書にアクセスする

credit_facilities = {1 : 'Yes',2:'No',3:'Not sure'} 

私は、辞書のキーとして使用する値を取得するモデルオブジェクトを持っています。たとえば、モデルの名前が "customer"で、属性が "credit_facility"であるとします。ですから、customer.credit_facilityは1,2を与えます。この値を辞書のキーとして使いたいと思います。つまり、次のエフェクトのためにdjangoテンプレート言語に相当するものがあります。その後、

class Customer(models.Model): 
    CREDIT_FACILITY_CHOICES = (
     (1, "Yes"), 
     (2, "No"), 
     (3, "Not sure") 
    ) 
    credit_facility = models.IntegerField(
     "credit facility", 
     choices = CREDIT_FACILITY_CHOICES 
     ) 

:ここ

>>> c = Customer(1) 
>>> c.get_credit_facility_display() 
"Yes" 

完全なドキュメント:

credit_facilities[customer.credit_facility] 
+0

カスタムテンプレートフィルタを作成する:投稿を参照してください:http://stackoverflow.com/questions/8000022/django-template-how-to-look-up-a-dictionary-value-with-a-variable – Wilfried

+2

これは、あなたのフィールドであれば、テンプレート内で 'customer.get_credit_facility_display'を実行することができます。 –

答えて

関連する問題