Python Lambda Functions
In this tutorial, we'll study anonymous functions, commonly called lambda functions. We'll understand what they are, how to execute them, and their syntax.
What are Lambda Functions in Python?
Lambda Functions in Python are anonymous functions, implying they don't have a name. The def keyword is needed to create a typical function in Python, as we already know. We can also use the lambda keyword in Python to define an unnamed function.
Syntax of Python Lambda Function
lambda arguments: expression
This function accepts any count of inputs but only evaluates and returns one expression.
Lambda functions can be used whenever function arguments are necessary. In addition to other forms of formulations in functions, it has a variety of applications in certain coding domains. It's important to remember that according to syntax, lambda functions are limited to a single statement.
Example of Lambda Function in Python
An example of a lambda function that adds 4 to the input number is shown below.
*Code to demonstrate how we can use a lambda function *
add = lambda num: num + 4
print( add(6) )
Output:
10
def add( num ):
return num + 4
print( add(6) )
Output:
10
To retrieve data from a table in Django using the lambda method, we can utilize the ORM (Object-Relational Mapping) capabilities provided by Django's models. Here's an example of how you can do it in six different ways:
Step 1: Define your Django model in models.py:
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
Step 2: Retrieve data from the table using different lambda methods in your view function in views.py:
Option 1: Basic Lambda Function
from django.shortcuts import render
from myapp.models import MyModel
def data_view(request):
data = MyModel.objects.all().values_list('name', flat=True)
return render(request, 'data.html', {'data': data})
output
<!DOCTYPE html>
<html>
<head>
<title>Data Template</title>
</head>
<body>
<h1>Data</h1>
<ul>
{% for item in data %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
Assuming the data list contains the following items:
data = ['John', 'Jane', 'Adam']
The corresponding HTML output in the template will be:
<ul>
<li>John</li>
<li>Jane</li>
<li>Adam</li>
</ul>
Option 2: Lambda Function with Filtering
from django.shortcuts import render
from myapp.models import MyModel
def data_view(request):
data = MyModel.objects.filter(age__gt=18).values_list('name', flat=True)
return render(request, 'data.html', {'data': data})
Option 3: Lambda Function with Mapping
from django.shortcuts import render
from myapp.models import MyModel
def data_view(request):
data = list(map(lambda obj: f"{obj.name} (Adult)" if obj.age > 18 else f"{obj.name} (Minor)", MyModel.objects.all()))
return render(request, 'data.html', {'data': data})
In the example above, the lambda function is used to transform each MyModel object retrieved from the database. The lambda function checks the age of each object and appends either "(Adult)" or "(Minor)" to the name based on the age condition.
The transformed data is stored in the data list and passed as a context variable to the data.html template.
When the data.html template is rendered, the for loop iterates over each item in the data list and displays it as a list item.
Make sure to adjust the lambda function and the fields you retrieve based on your specific requirements and the structure of your MyModel table.
renders in template file
<!DOCTYPE html>
<html>
<head>
<title>Data Template</title>
</head>
<body>
<h1>Data</h1>
<ul>
{% for item in data %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
Output
Each item in the data list is a string that has been transformed using the lambda function in the view. The lambda function adds the suffix "(Adult)" to the name if the age is greater than 18, otherwise it adds the suffix "(Minor)".
So, for example, if the data list contains the following items:
data = ['John (Adult)', 'Jane (Minor)', 'Adam (Adult)']
The corresponding HTML output in the template will be:
<ul>
<li>John (Adult)</li>
<li>Jane (Minor)</li>
<li>Adam (Adult)</li>
</ul>
Option 4: Lambda Function with Aggregation
from django.shortcuts import render
from myapp.models import MyModel
from django.db.models import Sum
def data_view(request):
total_age = MyModel.objects.all().aggregate(total_age=Sum('age'))
return render(request, 'data.html', {'total_age': total_age})
Some More Examples
Total age of all objects:
result1 = MyModel.objects.all().aggregate(total_age=Sum('age'))
Average age of all objects:
result2 = MyModel.objects.all().aggregate(avg_age=Avg('age'))
Maximum age among all objects:
result3 = MyModel.objects.all().aggregate(max_age=Max('age'))
Minimum age among all objects:
result4 = MyModel.objects.all().aggregate(min_age=Min('age'))
Count of objects:
result5 = MyModel.objects.all().aggregate(count=Count('id'))
Count of distinct ages:
result6 = MyModel.objects.all().aggregate(distinct_ages=Count('age', distinct=True))
Sum of ages for objects with name starting with 'J':
result7 = MyModel.objects.filter(name__startswith='J').aggregate(sum_age=Sum('age'))
Average age for objects with age greater than 30:
result8 = MyModel.objects.filter(age__gt=30).aggregate(avg_age=Avg('age'))
Maximum age among objects with name starting with 'A':
result9 = MyModel.objects.filter(name__startswith='A').aggregate(max_age=Max('age'))
Minimum age among objects with name starting with 'B':
result10 = MyModel.objects.filter(name__startswith='B').aggregate(min_age=Min('age'))
Count of objects with age less than 25:
result11 = MyModel.objects.filter(age__lt=25).aggregate(count=Count('id'))
Sum of ages for objects with name containing 'John':
result12 = MyModel.objects.filter(name__contains='John').aggregate(sum_age=Sum('age'))
Average age for objects with name ending with 'son':
result13 = MyModel.objects.filter(name__endswith='son').aggregate(avg_age=Avg('age'))
Maximum age among objects with age less than 50:
result14 = MyModel.objects.filter(age__lt=50).aggregate(max_age=Max('age'))
Minimum age among objects with age greater than 20:
result15 = MyModel.objects.filter(age__gt=20).aggregate(min_age=Min('age'))
Count of objects with age between 30 and 40:
result16 = MyModel.objects.filter(age__range=(30, 40)).aggregate(count=Count('id'))
Sum of ages for objects with name starting with 'S' or 'T':
result17 = MyModel.objects.filter(name__startswith__in=['S', 'T']).aggregate(sum_age=Sum('age'))
Average age for objects with name not equal to 'John':
result18 = MyModel.objects.exclude(name='John').aggregate(avg_age=Avg('age'))
Maximum age among objects with name not containing 'son':
result19 = MyModel.objects.exclude(name__contains='son').aggregate(max_age=Max('age'))
Minimum age among objects with name containing either 'a' or 'e':
Option 5: Lambda Function with Ordering
from django.shortcuts import render
from myapp.models import MyModel
def data_view(request):
data = MyModel.objects.order_by('name', '-age')
return render(request, 'data.html', {'data': data})
<!DOCTYPE html>
<html>
<head>
<title>Data Display</title>
</head>
<body>
<h1>Product List</h1>
{% if products %}
<ul>
{% for product in products %}
<li>{{ product.name }} - ${{ product.price }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
Option 6: Lambda Function with Complex Query
from django.shortcuts import render
from myapp.models import MyModel
def data_view(request):
data = MyModel.objects.filter(name__startswith='J').exclude(age__lt=30)
return render(request, 'data.html', {'data': data})
Some more Examples
from django.shortcuts import render
from myapp.models import MyModel
def data_view(request):
# Case-insensitive matching
data1 = MyModel.objects.filter(name__istartswith='J').exclude(age__lt=30)
# Case-sensitive matching
data2 = MyModel.objects.filter(name__startswith='j').exclude(age__lt=30)
# Matching any value in a list
data3 = MyModel.objects.filter(name__startswith__in=['J', 'K', 'L']).exclude(age__lt=30)
# Matching any value in a case-insensitive list
data4 = MyModel.objects.filter(name__istartswith__in=['j', 'k', 'l']).exclude(age__lt=30)
# Matching any substring
data5 = MyModel.objects.filter(name__contains='oh').exclude(age__lt=30)
# Matching any substring (case-insensitive)
data6 = MyModel.objects.filter(name__icontains='OH').exclude(age__lt=30)
# Matching any substring using regular expression
import re
data7 = MyModel.objects.filter(name__regex=r'^[A-Za-z]+o').exclude(age__lt=30)
# Matching any substring using case-insensitive regular expression
import re
data8 = MyModel.objects.filter(name__iregex=r'^[A-Za-z]+O').exclude(age__lt=30)
# Matching any substring using case-sensitive regular expression
import re
data9 = MyModel.objects.filter(name__regex=r'^[A-Z]+o').exclude(age__lt=30)
# Matching exact word
data10 = MyModel.objects.filter(name='John').exclude(age__lt=30)
# ... Add more query variations as needed ...
return render(request, 'data.html', {
'data1': data1,
'data2': data2,
'data3': data3,
'data4': data4,
'data5': data5,
'data6': data6,
'data7': data7,
'data8': data8,
'data9': data9,
'data10': data10,
# ... Add more query results ...
})
Step 3: Create a template file named data.html in the templates directory:
<html>
<head>
<title>Data Display</title>
</head>
<body>
<h1>Data from Table</h1>
{% if data %}
<ul>
{% for item in data %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endif %}
{% if total_age %}
<p>Total Age: {{ total_age.total_age }}</p>
{% endif %}
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Data Display</title>
</head>
<body>
<h1>Data from Table 1</h1>
{% if data1 %}
<ul>
{% for item in data1 %}
<li>{{ item.field1 }}</li>
{% endfor %}
</ul>
{% endif %}
<h1>Data from Table 2</h1>
{% if data2 %}
<ul>
{% for item in data2 %}
<li>{{ item.field2 }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
In this template file, we have conditions to check if the data list or total_age variable exists. If data exists, we display it as a list. If total_age exists, we display the total age.
Step 4: Define a URL pattern in urls.py to map to the data_view function.
from django.urls import path
from myapp.views import data_view
urlpatterns = [
path('data/', data_view, name='data
Top comments (0)