how to apply a custom function to a specific field in a number of queries in Django

Viewed 156

I have a simple model

class Person(models.Model): name = models.CharField(max_length=20,default="")

when I do Person.objects.all() I get Queryset with 20 results

I want to apply a custom function def foo(name): return "Hello" + str(name)

I don't want to use any loops is there any better method so that when I query I directly get these values

1 Answers

Yes, you can run all kind of functions on the DB directly. Django provides an API for that though Database Functions.

Here is how to archive your example. For that we will use the Concat function, which allows us to concatenate strings. We also need the Value function, which allows us to provide Python variables directly to the DB. Finally, we are using annotate to add a calculated field to a queryset.

from django.db.models import Value
from django.db.models.functions import Concat

Person.objects.annotate(name_plus=Concat(Value("Hello"), "name"))
Related