如何在django查询中使用正则表达式

时间:2022-02-28 15:45:44

In the database image names are saved in the below format.

在数据库中,图像名称以下面的格式保存。

+------------+------------+------------+-----------+
| adv_images | start_date | end_date   |        id |
+------------+------------+------------+-----------+
| 1.jpg      | 2013-05-22 | 2013-05-28 |        64 |
| 1a.jpg     | 2013-05-22 | 2013-05-28 |        64 |
| 1b.jpg     | 2013-05-22 | 2013-05-28 |        64 |
| 1c.jpg     | 2013-05-22 | 2013-05-28 |        64 |
| 2.jpg      | 2013-05-22 | 2013-05-28 |        64 |
| 2a.jpg     | 2013-05-22 | 2013-05-28 |        64 |
| 2b.jpg     | 2013-05-22 | 2013-05-28 |        64 |
| 2c.jpg     | 2013-05-22 | 2013-05-28 |        64 |
| 3.jpg      | 2013-05-22 | 2013-05-28 |        64 |
| 3a.jpg     | 2013-05-22 | 2013-05-28 |        64 |
| 3b.jpg     | 2013-05-22 | 2013-05-28 |        64 |
+------------+------------+------------+-----------+

I want to pull the data from db group by 'adv_images', for ex- here its showing 11 records in the db, but i want to pull only 3 i.e(1.jpg, 2.jpg and 3.jpg). Basically 1, 2, 3 are the main images of an album and 1a, 1b, 2a, 2b etc are the sub images. I am trying to use regular expression in django query , but no success. I also want to pull the count for the number of images per album. like for album 1 nd 2 the count will be 4 and for album 3 the count will be 3.

我想通过'adv_images'从数据库组中提取数据,因为它在数据库中显示了11条记录,但我想只拉3即(1.jpg,2.jpg和3.jpg)。基本上1,2,3是专辑的主要图像,1a,1b,2a,2b等是子图像。我试图在django查询中使用正则表达式,但没有成功。我还要计算每张专辑的图像数量。对于专辑1和2,计数将是4,而对于专辑3,计数将是3。

N:B: The image names are always starts with a digit.

N:B:图像名称始终以数字开头。

1 个解决方案

#1


6  

As for the first problem you can use the regex operator the Django ORM provides

至于第一个问题,你可以使用Django ORM提供的正则表达式运算符

e.g.

例如

Model.objects.filter(adv_images__regex=r'^\d+')[:3]

Should output the first 3 rows depending on the ordering you have set.

应根据您设置的顺序输出前3行。

To only select the whole number records the simplest solution is probably

要仅选择整数记录,可能是最简单的解决方案

Model.objects.filter(adv_images__regex=r'^\d\.')[:3]

As for the second problem, does the digit represent an unique album identifier, or is your snippet missing a relational field?

至于第二个问题,数字代表一个唯一的专辑标识符,或者你的代码片段是否缺少关系字段?

#1


6  

As for the first problem you can use the regex operator the Django ORM provides

至于第一个问题,你可以使用Django ORM提供的正则表达式运算符

e.g.

例如

Model.objects.filter(adv_images__regex=r'^\d+')[:3]

Should output the first 3 rows depending on the ordering you have set.

应根据您设置的顺序输出前3行。

To only select the whole number records the simplest solution is probably

要仅选择整数记录,可能是最简单的解决方案

Model.objects.filter(adv_images__regex=r'^\d\.')[:3]

As for the second problem, does the digit represent an unique album identifier, or is your snippet missing a relational field?

至于第二个问题,数字代表一个唯一的专辑标识符,或者你的代码片段是否缺少关系字段?