在Django python中,以下查询的等价物是什么?

wsxa1bj1  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(152)

SELECT REPLACE(field1,pattern,"<span style='background-color:yellow'>" + pattern + "</span>"),REPLACE(field2,pattern,"<span style='background-color:yellow'>" + pattern + "</span>")FROM table_name WHERE field1 LIKE '%pattern%' OR field2 LIKE '%pattern%';
以下是我的模型。如何在django python中编写SQL代码?

class news(models.Model):
    dbemail = models.CharField(max_length=100)
    dbsubject = models.CharField(max_length=300)
    dbdetail = models.CharField(max_length=5000)
    dbimage = models.CharField(max_length=100)
    dbdatetime = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return "Email: " + self.dbemail + " | Subject: " + self.dbsubject + " | datetime: " + str(self.dbdatetime)

我想查询dbsubject和dbdetail,并在查询中用另一个文本替换一个文本,然后返回结果。
这就是我所做的,但它并没有完成这项工作:
用户新闻=新闻.对象.过滤器(dbsubject__contains=搜索).order_by('-dbdatetime').values()

bnl4lu3b

bnl4lu3b1#

我的老师拉希姆发现了答案如下:

usernews = news.objects.filter(
        Q(dbsubject__contains=search) | Q(dbdetail__contains=search)
        ).annotate(
        newdbsubject=Replace('dbsubject', Value(search), Value("<span style='background-color:yellow'>" + search + "</span>")),
        newdbdetail=Replace('dbdetail', Value(search), Value("<span style='background-color:yellow'>" + search + "</span>"))
        ).order_by('-dbdatetime').values()

相关问题