スキップしてメイン コンテンツに移動

投稿

11月, 2021の投稿を表示しています

Djangoで多段かつ複数チェックボックスにて絞り込みをおこなう

今回もタイトル通りですが、ネットで検索しても多段・複数チェックボックスを用いての例がほとんどみつかりませんでした。チェックボックスについては一段の例はあったのですが、やってみたところ、簡易的に多段かつ複数の絞り込みができたので、備忘録として挙げてみました。 早速ですが以下models.pyです。 class mb_basic_spec(models.Model): class Meta: managed = False db_table = 'mb_basic_spec' art_id = models.BigIntegerField(primary_key=True, db_column='art_id') art_name = models.TextField() chipset_vendor = models.CharField(max_length=128) chipset = models.CharField(max_length=128) vendor = models.CharField(max_length=128) cpu_socket = models.CharField(max_length=128) form_factor = models.CharField(max_length=128) memory_form = models.CharField(max_length=128) memory_type = models.CharField(max_length=128) class v_vendor(models.Model): class Meta: managed = False db_table = 'view_vendor' vendor_id = models.IntegerField(primary_key=True, db_column='vendor_id') vendor = models.CharField(max_length=128) class v_chipset

項目可変長の縦持ち属性テーブルを属性毎にviewを作成し横持ちにして扱う

ほぼタイトルの通りですが、メインテーブルのマスターレコードに対し、複数の属性レコードで項目が可変長の属性テーブルがあり、これを、横持ちのデータとして取り扱う必要がありました。最初はPivotを使おうかと思いましたが、項目が可変長なので、うまくいきません。そこで、属性種別ごとにviewを用いてマスターレコード単位でに横持ちにし、さらにマスターレコードidを頼りに、複数のviewをinnerjoinで複数結合させたところ、ほぼ目的通りに動作したので、備忘録代わりに挙げてみることにしました。 属性テーブルは一例として以下の様になっています。 select * from art_prop where art_id=1; +-------------+------------------+--------------+---------------+------------------+----------------+-----------+-----------+--------+ | art_prop_id | prop_cat | prop_name | prop_dsc1 | prop_dsc2 | prop_dsc3 | prop_dsc4 | prop_dsc5 | art_id | +-------------+------------------+--------------+---------------+------------------+----------------+-----------+-----------+--------+ | 1 | Basic spec | vendor | ASRock | | | | | 1 | | 2 | Basic spec | form factor | Micro ATX | | | | | 1 | |

Djangoでサブフォームがある場合について

サブフォーム側に複数レコードがあり、なおかつ複数サブフォームを使う必要があり、はじめはインラインフォームをつかってできないかとおもいやっていたのですが、登録はともかく、更新などがうまくいきませんでした。そこでしらべたところ、ほぼそのままなんですが、 こちらの記事 を参考にしたところ、(ありがとうございます m(__)m) django-extra-viewsを使うことで凡そのことができたので、備忘録として挙げてみました。 まず、django-extra-viewsをインストールします。debianではpython3-django-extra-viewsパッケージがあるので、これをインストールしておきます。 つづいてviews.pyとforms.pyですが以下の様にしました。 #views.py class artCreateView(CreateWithInlinesView): model = art fields = ('art_name', 'cat1', 'cat2', 'cat3', 'cat4', 'url1', 'url2',) context_object_name = 'art' inlines = [art_propForm] template_name = 'myapp/edit.html' success_url = reverse_lazy('pc:top') factory_kwargs = { 'can_order': True, 'can_delete': True} class artUpdateView(UpdateWithInlinesView): model = art form_class = artForm inlines = [art_propForm] template_name = 'myapp/edit.html' success_url = reverse_lazy('pc:top')