Django模型 Q对象实现复杂查找,对于初学者来说感觉有一种陌生感。不过我们要进行复杂查找时,就到了它的用武之地了。

  或许你想在filter()里面使用或条件...纠结在django中怎么实现...

  接下来,分享Q对象实现复杂查找。

  适用情况:执行更复杂的查询(比如,实现筛选条件的 OR、AND 关系)

  例子:

 models如下:

1 class Article(models.Model):
2     headline = models.CharField(max_length=50)
3     pub_date = models.DateTimeField()<br><br><br><br>想查询headline字段开头以'hello',或者结尾以'Goodbye'的数据。<br><br>代码实现:
1 Article.objects.filter(Q(headline__startswith='Hello') | Q(headline__startswith='Goodbye'))

 

 

AND的实例:

1 Article.objects.filter(~Q(pk=self.a1) & ~Q(pk=self.a2))

 

分享一个比较全面的demohttps://github.com/django/django/blob/master/tests/modeltests/or_lookups/tests.py

相关文章:

  • 2022-02-08
  • 2021-10-18
  • 2021-11-12
  • 2022-12-23
  • 2021-07-04
  • 2021-06-20
  • 2022-12-23
  • 2021-05-23
猜你喜欢
  • 2022-02-26
  • 2023-03-04
  • 2021-08-08
  • 2021-09-24
相关资源
相似解决方案