【问题标题】:django filter queryset based on __str__ of modeldjango 基于模型的 __str__ 过滤查询集
【发布时间】:2016-11-22 11:32:05
【问题描述】:

我有以下型号:

class Subspecies(models.Model):
    species = models.ForeignKey(Species)
    subspecies = models.CharField(max_length=100)

    def __str__(self):
        return self.species.species_english+" "+self.species.species+" "+self.subspecies

    def __unicode__(self):
        return self.species.species_english+" "+self.species.species+" "+self.subspecies

请注意,ForeignKey 字段 species__str____unicode__ 方法中使用。我做了这个过滤查询:

l = list(Subspecies.objects.filter(subspecies__contains=request.GET.get('term')).order_by('subspecies')[:10])

这几乎是我想要的,除了不完全。我真正想要的是一个过滤器,它检查对象的__str__ 表示是否包含某些字符组,而不仅仅是检查subspecies 字段。而不是subspecies__contains=...,而是__str____contains=...,但这当然行不通。

这可能吗?如果是这样,我将如何进行此查询?

谢谢!

【问题讨论】:

  • 为什么不能只过滤相关模型中的三个字段?
  • 是的,这就是我最终所做的,我宁愿能够一起搜索整个短语,但使用 OR 单独过滤几乎可以。

标签: python django filter django-queryset


【解决方案1】:

Filter 生成要在 DB 中执行的查询。

__str__ 在 Python 解释器中运行。你不能从数据库调用它。 所以简短的回答是“不,你不能”。您必须手动过滤它,例如使用 filter 内置函数。

【讨论】:

  • 谢谢。我以前很怕那个。该模型包含大约 20K 行。我在shell中尝试了这个,但花了相当长的时间。 [i for i in Subspecies.objects.all() if 'aur' in unicode(i)] DB过滤方法很快。对于网络来说可能太慢了。
  • 类似的性能不佳:a = filter(lambda x: 'aur' in unicode(x), s.objects.all()) :-/
  • 你可以使用原始 SQL 表达式来进行这样的查询,比如... WHERE species_english || species || subspecies CONTAINS ...
  • 我注意到有一种方法可以在其中编写 SQL。为了得到它,我可以使用concat 将字段组合成一个字符串。谢谢!
【解决方案2】:

我在这里找到的最佳方法是用引号 (' ') 标记您的目标。然后对字符串进行切片并根据它进行过滤..这就是你的情况

class Subspecies(models.Model):
    species = models.ForeignKey(Species)
    subspecies = models.CharField(max_length=100)

def __str__(self):
    return self.species.species_english+" "+self.species.species+" "+" 'str(self.subspecies)'"

def __unicode__(self):
    return self.species.species_english+" "+self.species.species+" "+" 'str(self.subspecies)'"

如您所见,您的 subspecies 部分现在介于 ' ' 之间

然后你根据它进行下一步过滤:

sub_input = request.GET.get('term')
sub = sub_input .split("'")[1::2] #not sure how did [1::2] works but it is the only way that worked for me 
l = Subspecies.objects.filter(subspecie=sub[0]) #used indexing as split gives you result as a list

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 2023-03-17
    • 1970-01-01
    • 2019-01-12
    • 2015-04-01
    • 2018-09-01
    • 2019-03-29
    • 2020-10-22
    • 2019-07-31
    相关资源
    最近更新 更多