Debug School

rakesh kumar
rakesh kumar

Posted on

How to get data from multiple table using list comprehension and lambda function in django

Using lambda function

Step 1: Define Django models to represent your tables. In your models.py file:

from django.db import models

class Table1(models.Model):
    field1 = models.CharField(max_length=100)
    field2 = models.CharField(max_length=100)

    def __str__(self):
        return self.field1

class Table2(models.Model):
    field3 = models.CharField(max_length=100)
    field4 = models.CharField(max_length=100)

    def __str__(self):
        return self.field3

class Table3(models.Model):
    field5 = models.CharField(max_length=100)
    field6 = models.CharField(max_length=100)

    def __str__(self):
        return self.field5
Enter fullscreen mode Exit fullscreen mode

In the above code, we define three models: Table1, Table2, and Table3, each representing a table with their respective fields.

Step 2: Create some sample data in your database tables. You can either use Django's shell or create a Django management command to populate the tables with data.

Step 3: Create a Django view that retrieves data from the tables using a lambda function with multiple if conditions and passes it to the template. In your views.py file:

from django.shortcuts import render
from .models import Table1, Table2, Table3

def retrieve_data(request):
    data = list(filter(lambda x: (x.field1 == 'Value1' and x.field2.startswith('A')) or (x.table2.field3 == 'Value2' and x.table2.field4.endswith('B')) or (x.table3.field5 == 'Value3' and x.table3.field6.isnumeric()), Table1.objects.select_related('table2', 'table3')))
    return render(request, 'data.html', {'data': data})
Enter fullscreen mode Exit fullscreen mode

In the above code, we use a lambda function with the function to retrieve the data from the Table1 table. The lambda function applies multiple conditions using and and or operators to each object in the result set. The function returns only the objects for which any of the conditions evaluate to True. The resulting data is converted to a list.

Step 4: Create a Django template (data.html) to display the retrieved data. In your template:

<html>
<head>
    <title>Data Retrieval Example</title>
</head>
<body>
    <h1>Data Retrieval Example</h1>
    <table>
        <thead>
            <tr>
                <th>Field 1</th>
                <th>Field 2</th>
            </tr>
        </thead>
        <tbody>
            {% for item in data %}
            <tr>
                <td>{{ item.field1 }}</td>
                <td>{{ item.field2 }}</td>
                <td>{{ item.table2.field3 }}</td>
                <td>{{ item.table2.field4 }}</td>
                <td>{{ item.table3.field5 }}</td>
                <td>{{ item.table3.field6 }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the template, we iterate over the data list using aloop. Each item in the list is an object of Table1. We access the fields of the object using item.field1 and item.field2 to display them in the table.

Step 5: Add a URL pattern in your urls.py file to map the view. In your urls.py file:

from django.urls import path
from .views import retrieve_data

urlpatterns = [
    path('retrieve-data/', retrieve_data, name='retrieve_data'),
]
Enter fullscreen mode Exit fullscreen mode

Using list Comprhension

Step 1: Define Django models to represent your tables. In your models.py file:

from django.db import models

class Table1(models.Model):
    field1 = models.CharField(max_length=100)
    field2 = models.CharField(max_length=100)

    def __str__(self):
        return self.field1

class Table2(models.Model):
    field3 = models.CharField(max_length=100)
    field4 = models.CharField(max_length=100)

    def __str__(self):
        return self.field3

class Table3(models.Model):
    field5 = models.CharField(max_length=100)
    field6 = models.CharField(max_length=100)

    def __str__(self):
        return self.field5
Enter fullscreen mode Exit fullscreen mode

Step 2: Create some sample data in your database tables. You can either use Django's shell or create a Django management command to populate the tables with data.

Step 3: Create a Django view that retrieves data from multiple tables using list comprehension with multiple if conditions and passes it to the template. In your views.py file:

from django.shortcuts import render
from .models import Table1, Table2, Table3

def retrieve_data(request):
    data = [
        {
            'field1': item.field1,
            'field2': item.field2,
            'field3': item.table2.field3,
            'field4': item.table2.field4,
            'field5': item.table3.field5,
            'field6': item.table3.field6
        }
        for item in Table1.objects.all()
        if (item.field1 == 'Value1' and item.field2.startswith('A')) or (item.table2.field3 == 'Value2' and item.table2.field4.endswith('B')) or (item.table3.field5 == 'Value3' and item.table3.field6.isnumeric())
    ]
    return render(request, 'data.html', {'data': data})
Enter fullscreen mode Exit fullscreen mode

In the above code, we use list comprehension to retrieve the data from the Table1 table. The list comprehension applies multiple conditions using and and or operators to each object in the result set. Additionally, we access related fields from Table2 and Table3 using the table2 and table3 attributes of the Table1 objects. The resulting data is stored in a list of dictionaries.

Step 4: Create a Django template (data.html) to display the retrieved data. In your template:

<html>
<head>
    <title>Data Retrieval Example</title>
</head>
<body>
    <h1>Data Retrieval Example</h1>
    <table>
        <thead>
            <tr>
                <th>Field 1</th>
                <th>Field 2</th>
                <th>Field 3</th>
                <th>Field 4</th>
                <th>Field 5</th>
                <th>Field 6</th>
            </tr>
        </thead>
        <tbody>
            {% for item in data %}
            <tr>
                <td>{{ item.field1 }}</td>
                <td>{{ item.field2 }}</td>
                <td>{{ item.field3 }}</td>
                <td>{{ item.field4 }}</td>
                <td>{{ item.field5 }}</td>
                <td>{{ item.field6 }}</td>
            </tr>
            {% endfor %}
        </tbody>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)