Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset filter after a concatenation of two columns

Tags:

Is there any way to filter a model using a concatenation of two of its columns? My model is like this:

class Item(models.Model):     series = models.CharField(max_length=50)     number = models.CharField(max_length=50) 

What I need is to filter after the concatenation of the two columns, if a user inputs A123 I want to be able to find any Item that has series and number like %A and 123% or %A1 and 23% Is this possible using the django models? Or is it possible with raw sql? I would rather not construct a new column with the concatenation.

like image 663
Virgil Balibanu Avatar asked Sep 14 '15 07:09

Virgil Balibanu


People also ask

Can I filter a QuerySet Django?

With the Django QuerySet class, you can apply filters that return QuerySets defined by your filters. The filter() method returns all objects that match the keyword arguments given to the method.

How can I combine two or more QuerySets in a Django view?

The Solution You can also use the chain() method from the Itertools module, which allows you to combine two or more QuerySets from different models through concatenation. Alternatively, you can use union() to combine two or more QuerySets from different models, passing all=TRUE if you want to allow duplicates.


1 Answers

In addition to what was said earlier, example:

from django.db.models import Value from django.db.models.functions import Concat queryset = Item.objects.annotate(search_name=Concat('series', Value(' '), 'number')) # then you can filter: queryset.filter(search_name__icontains='whatever text') 
like image 159
bilabon Avatar answered Nov 09 '22 04:11

bilabon