Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regex in django query

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.

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

like image 505
sandeep Avatar asked May 03 '13 12:05

sandeep


1 Answers

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

e.g.

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

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

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?

like image 103
Hedde van der Heide Avatar answered Sep 20 '22 14:09

Hedde van der Heide