【问题标题】:Filter django queryset over a concatenated extra field在连接的额外字段上过滤 django 查询集
【发布时间】:2013-06-05 10:21:38
【问题描述】:

我有以下(缩短的)Django 模型:

class File(models.Model):
    name = models.TextField()
    directory = models.ForeignKey(Directory)

class Directory(models.Model):
    path = models.TextField()

用户通常会将文件显示为path + '/' + name, f.e. '/bin' + '/' + 'bash' => '/bin/bash'。我不想提供搜索字段来查找文件。

如果我使用 Q()-Objects,我可以在路径或名称中搜索匹配项,但如果用户搜索 '/bin/bash',它将失败。

到目前为止,我想出了:

files = File.objects.extra(select={'fullpath': 'path || "/" || name'},
    tables=['directories'], order_by= ['fullpath']).distinct()

不幸的是,这会首先将所有目录与所有文件名连接起来,而不仅仅是那些实际存在的目录。此外,我无法添加另一个过滤器

.filter(fullpath__icontains=query)

因为我无法引用额外字段。

如果可能的话,我想继续使用 django OR-Mapper,而不是在数据库上执行原始 SQL。

感谢所有建议

【问题讨论】:

    标签: django django-queryset


    【解决方案1】:

    您可以额外使用 DB 函数 concat,因为在我的情况下,我已经这样做来连接日期。

    Event.objects.all().order_by('-start_time').extra(select={'date':'concat(year(start_time),\"/\",month(start_time),\"/\",day(start_time))','time':'concat(hour(start_time),\":\",minute(start_time))','program_no':'program_id'}).values('id','program_no','event_type__name','venue__city','venue__state','venue__website','series_id','date','time')
    

    希望这会对你有所帮助。

    谢谢。

    【讨论】:

    • 感谢您的回答。提出这个问题的项目现已完成并交付;我不再有权访问代码或需要更改它。不过,如果我再次遇到这个问题,我会记住这一点。
    猜你喜欢
    • 2015-04-03
    • 2017-03-09
    • 1970-01-01
    • 2010-12-13
    • 2019-02-17
    • 2013-03-08
    • 2022-11-01
    • 2011-12-21
    • 2015-05-06
    相关资源
    最近更新 更多