Django - メソッドを反復処理できますか?私は製品、価格と統計などと連携ジャンゴでのWebアプリケーションに取り組んでいます
EDIT: もっとstraighforward説明:どのように「グループ」や「マーク」インスタンスメソッドのいくつかのように、私はへそれらを反復することができますfor method in instance.name_of_the_group
私はモデルProduct
を持っています。 Product
には複数の属性とメソッドがあります。これらのメソッドの中には、「統計」データを返すものがあります。
class Product(models.Model):
name = ...
...
def save(...
...
def get_all_colors(self):
....
def get_historical_average_price(self): #statistic method
price = <some calculation>
return price
def get_historical_minimal_price(self): #statistic method
...
return price
のでget_historical_average_price
とget_historical_minimal_price
のようなメソッドがたくさんあります。
ここでは、ラベルを書き、プロジェクト内でこれらのメソッドを1つずつ呼び出す必要があります。たとえば、テーブルを生成したり、XMLエクスポートを作成したりするときなどです。
私はいくつかの方法がありますので、私は彼らがfor
などのループ
を使用して作業することができるだろう何とか「マーク」はそれらをものは「統計的」な方法であることを、彼らにいくつかの名前を与えることができるようにしたいと思いますそれをするには? XMLジェネレータに
例:
<statistics>
{% for statistic_method in product.statistics %}
<{{ statistic_method.name }}>{{ statistic_method }}</{{ statistic_method.name }}>
{% endfor %}
</statistics>
の代わり:よう
<products>
{% for product in products %}
<product>
<code>{{ product.code }}</code>
<name>{{ product.name }}</name>
<statistics>
<historical_average>{{ product.get_historical_average_price}}</historical_average>
<minimal_price>{{ product.get_historical_minimal_price}}</minimal_price>
</statistics>
</product>
{% endfor %}
</products>
だから私が何かをするだろう。これは、カスタムを使用するための偉大なユースケースである
<statistics>
<historical_average>{{ product.get_historical_average_price}}</historical_average>
<minimal_price>{{ product.get_historical_minimal_price}}</minimal_price>
</statistics>
ありがとうございますが、私が上記で書いたXMLジェネレータの例でどのように使用できるのか分かりません。これらのメソッドは、テーブル生成などで使用するための属性method.programmatic_name(xml使用の場合はhistorical_average_price)、メソッド生成の場合はmethod.label(Historical AVG price)のようなものが必要です。 –
ああ、おそらく私は知っています。ラベル= ...などのようなメソッドに属性を追加することができます。 –
ええ、そうです。実際にはどの機能を使用するのと同じですが、ドット表記を使用しています。それが一般的であれば、XMLフラグメントをモデルマネージャーに書き込むことができます。クエリーセットを返す必要はありません。 :) – Withnail