0

ビュー.py

def search(request):
    reportlist = []
    loc_id = request.POST.get('location')
    if loc_id:
        location_list = ReportLocation.objects.filter(title=loc_id)
        for locaton in location_list:                       
            reportlist.append(locaton.report)

フォーム.py

class SearchFilterForm(Form):
    location = forms.ChoiceField(widget=forms.Select(), choices='',required=False, initial='Your name')

    def __init__(self,user_id, *args, **kwargs):
        super(SearchFilterForm, self).__init__(*args, **kwargs)
        self.fields['location'] = forms.ChoiceField(choices=[('','All Location types')]+[(loc.id, str(loc.title)) for loc in Location.objects.filter(user=user_id).exclude(parent_location_id=None)])

models.py

class ReportLocation(models.Model):   
    report = models.ForeignKey(Report)    
    title = models.CharField('Location', max_length=200)

選択した選択肢でReportLocationフィールドのタイトルフィールドをフィルタリングする方法.views.pyで上記のフィルタクエリを試しましたが、フィルタリングされたデータが表示されません.助けが必要

4

1 に答える 1

1

フォームは、場所のタイトルではなく、値のキーに場所 ID を使用しています。ChoiceFields は、choices 内の各タプルの最初の部分を POST される値として使用し、各タプルの 2 番目の部分は、ユーザーに表示される選択肢の名前にすぎません。あなたの値を確認するためにprintステートメントを追加するloc_idと、私が何を意味するかがわかります。

そのため、 でロケーション ID のロケーション タイトルを検索する必要がありますrequest.POST。ReportLocation モデルに Location への ForeignKey がある場合、次のようなことができます

location_list = ReportLocation.objects.filter(location__id=loc_id)

ただし、それがスキーマで機能しない場合は、別のクエリとしてタイトルを検索する必要がある場合があります。簡単な例を次に示します。

def search(request):
    reportlist = []
    loc_id = request.POST.get('location')
    if loc_id:
        # This will cause an error if loc_id isn't found,
        # it's just here as an example
        loc_title = Location.objects.get(id=loc_id).title
        location_list = ReportLocation.objects.filter(title=loc_title)
        for locaton in location_list:                       
            reportlist.append(locaton.report)
于 2013-08-17T00:29:22.633 に答える