【问题标题】:filter the data from database using django filter使用 django 过滤器过滤数据库中的数据
【发布时间】:2013-08-19 11:18:30
【问题描述】:

views.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)

forms.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 中使用上述过滤器查询,但未显示任何过滤后的数据。需要帮助

【问题讨论】:

  • 你的title包含id字段?这很奇怪......

标签: django django-models django-forms django-templates


【解决方案1】:

您的表单使用位置 ID 作为其值键,而不是位置标题。 ChoiceFields 在选择中使用每个元组的第一部分作为发布的值,每个元组的第二部分只是用户看到的选项的名称。添加一个打印语句来检查你的loc_id 的值,你就会明白我的意思了。

因此,您需要在request.POST 中查找位置 ID 的位置标题。如果您的 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-07-18
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2019-03-18
    • 2014-08-06
    • 2021-12-19
    相关资源
    最近更新 更多