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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With