我的目标是使用用户通过搜索表单发送的值从books表返回行.搜索表单包含多个字段"作者"、"ISBN"和"标题".

NB: In the code, the author field is a char, but converted to ID based on authors name due to foreign key relation.

在这段代码中,有一个get请求被转换为Dictionary,并被转换为允许它从books表中查询数据.

def search(request):

    form = BooksForm()

    if request.method == 'GET':

        # convert get request to dictionary
         book_search = dict(request.GET)
         print("data before cleaning", book_search)

       #get the name from the dictionary get request
         author_name =request.GET['author']
       
        #get the author id from the author table
         author = Author.objects.filter(full_name__contains=author_name).values()

         #get author_id from author queryset
         author_id = author[0]['id']

      #update the dict with the author id to allow search in books models (foreing key)
         book_search['author'] = author_id
         print("data after cleaning",book_search)

         result_set = Book.objects.filter(**book_search)

         print("book search queryset",result_set)

问题:

推荐答案

请允许筛选任意密钥.这使得视图对request forgery敏感,例如,用户可以使用author__gender作为键,F作为值发出请求,从而可以公开您可能想要隐藏的数据.

您可以使用像django-filter [GitHub]这样的库来确定如何过滤查询集.您可以在此处创建一个如下所示的过滤器:

import django_filters

class BookFilter(django_filters.FilterSet):
    author = django_filters.CharFilter(
        field_name='author__full_name',
        lookup_expr='contains'
    )

    class Meta:
        model = Book
        fields = ['isbn']

有了这个过滤器,它将只使用request.GET中的authorisbn键,从而忽略可能要过滤敏感数据的其他键.

然后,您可以将其用于:

def search(request):
    book_filter = ProductFilter(request.GET)
    print('book search queryset', book_filter.qs)
    return render(request, 'name-of-template.html', {'book_filter': book_filter})

然后,在模板中,可以使用{{ book_filter.form }}表示基于过滤器的表单,使用{% for item in book_filter.qs %} … {% endfor %}枚举过滤查询集中的项目.

Python相关问答推荐

正在设置字段.需要为假,因为错误列表索引必须是整数或切片,而不是字符串

Django关于UniqueBindition的更新

取相框中一列的第二位数字

Django序列化器没有验证或保存数据

仅对matplotlib的条标签中的一个条标签应用不同的格式

如何将Matplotlib的fig.add_axes本地坐标与我的坐标关联起来?

Tkinter滑动条标签.我不确定如何删除滑动块标签或更改其文本

如何防止Plotly在输出到PDF时减少行中的点数?

Pandas 第二小值有条件

为什么我的Python代码在if-else声明中的行之前执行if-else声明中的行?

Python 约束无法解决n皇后之谜

_repr_html_实现自定义__getattr_时未显示

删除所有列值,但判断是否存在任何二元组

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

基于字符串匹配条件合并两个帧

Pandas计数符合某些条件的特定列的数量

Scrapy和Great Expectations(great_expectations)—不合作

如何在表中添加重复的列?

提取相关行的最快方法—pandas

在单个对象中解析多个Python数据帧