Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a query where it filters everything that starts with a number in Django?

I have a model called Book with a Title Field.

class Book(models.Model):
    title = models.CharField(null = False,blank=False)

Now I need a filter to get all books with titles starting with a number.

This works but how will I extend the queryset?

b = Book.objects.filter(title__startswith = 1).order_by('title')

This doesn't work

b = b + Book.objects.filter(title__startswith = 2).order_by('title')

or this

b.extend(Book.objects.filter(title__startswith = 2).order_by('title'))
like image 947
Joseph Lafuente Avatar asked Sep 22 '11 18:09

Joseph Lafuente


1 Answers

You can use a regular expression as a query parameter to check that the a value starts with a number:

Book.objects.filter(title__regex=r'^\d')
like image 99
Daniel Roseman Avatar answered Nov 15 '22 01:11

Daniel Roseman