Dive into Code

Discover code snippets, tutorials, and programming insights

Django

Generate Django table dynamically

<p>Function to create an html table of a django queryset dynamically.</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from django.urls import reverse,reverse_lazy, NoReverseMatch, resolve
from django.utils.safestring import mark_safe
from django.db.models.fields.files import ImageFieldFile, FileField
from decimal import Decimal
from django.utils.html import format_html

def get_rows(fields, object_list):
    '''
    fields : [{'verbose_name': 'Name', 'db_name': 'name'}]
    object_list : queryset
    '''
    table = "<table class='table table-striped'>"
    thead = '<thead><tr>'
    for field in fields:
        thead += f"<th>{field['verbose_name']}</th>"
    thead += '</tr></thead>'    
    table += thead + '<tbody>'
    for obj in object_list:
        print(obj._meta.fields)
        app = obj._meta.app_label
        model = obj.__class__.__name__.lower()
        update_url = reverse_lazy(f"{app}:{model}-update",kwargs={"pk":obj.pk})
        delete_url = reverse_lazy(f"{app}:{model}-delete",kwargs={"pk":obj.pk})
        tr = '<tr>'
        for field in fields:
            db_name = field['db_name']
            value = getattr(obj, db_name)
            if isinstance(value, Decimal):
                value = round(value,0)
            elif isinstance(value, bool):
                if value:
                    value = format_html(mark_safe('<i class="bi bi-check-lg text-success"></i>'))
                else:
                    value = format_html(mark_safe('<i class="bi bi-x-lg text-danger"></i>'))
            elif isinstance(value, models.Manager):
                print(f"{value} is a related manager.")
                related_objects = value.get_queryset()
                value = '<ul>'
                for obj in related_objects:
                    value += f'<li>{obj}</li>'
                value += '</ul>'
            elif isinstance(value,ImageFieldFile):
                if value and value.url:
                    value = format_html(mark_safe('<img src="{}" width="100px" />'.format(value.url)))
            tr += '<td>' + str(value) + '</td>'
        tr += f"""<td><a href='{update_url}'>{format_html(mark_safe('<i class="bi bi-pencil-square text-warning" style="font-size:1.5rem;"></i>'))}</a><a href='{delete_url}        'class='delete-tr'>{format_html(mark_safe('<i class="bi bi-x text-danger" style="font-size:1.5rem;"></i>'))}</a></td>"""
        
        tr += '</tr>'
        table += tr
    table += '</tbody></table>'
    return table
Django

Django iterate model object dynamically

<p>This snippet can be used to iterate a model object in django&nbsp; dynamically&nbsp;</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def get_obj(obj):
    from django.db import models
    app_label = obj._meta.app_label
    print(app_label)
    fields = obj._meta.get_fields()
    for field in fields:
        if hasattr(obj,field.name):
            value = getattr(obj,field.name)
            if isinstance(field,models.ForeignKey):
                print(field.remote_field.model)
            elif isinstance(value,models.Manager):
                related_objects = value.get_queryset()
                for r_obj in related_objects:
                    print(r_obj)
            else:
                print("name==>",field.name, "value==>",value)
  
my_obj = Model.objects.get(id=1)
get_obj(my_obj)
Python

Psycopg2 insert or update json object

<p>Insert or update json&nbsp; object in psycopg2</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def insert_update_json(db_table, column, obj, json_key, search_value):
    try:
        # Check if a record with the specified value in the search_column already exists
        cursor.execute(f"SELECT id FROM {db_table} WHERE {column}->>'{json_key}' = %s", (search_value,))
        existing_data = cursor.fetchone()

        if existing_data:
            # Update existing record
            cursor.execute(
                f"UPDATE {db_table} SET {column} = %s WHERE id = %s",
                (json.dumps({**obj}, ensure_ascii=False, cls=DecimalEncoder), existing_data[0])
            )
        else:
            # Insert new record
            cursor.execute(
                f"INSERT INTO {db_table} ({column}) VALUES (%s)",
                (json.dumps({**obj}, ensure_ascii=False, cls=DecimalEncoder),)
            )

        # Commit the transaction
        connection.commit()

    except Exception as e:
        # Handle exceptions, log errors, and rollback the transaction
        print(f"Error: {e}")
        connection.rollback()
Python

Psycopg2 reset tables

<p>To reset tables in postgresql with psycopg2 you can use&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

connection = psycopg2.connect(user=User,
                                password=Paswd,
                                host=Host,
                                port=Port,
                                database=Db)
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cursor = connection.cursor()


def reset_tables(tables):
    for table in tables:
        delete_query = f"DELETE FROM {table};"
        cursor.execute(delete_query)
        cursor.execute(f'TRUNCATE {table} RESTART IDENTITY;')
        cursor.execute(f'ALTER SEQUENCE {table}_id_seq RESTART WITH 1;')
        connection.commit()

tables = ['table1', 'table2']
reset_tables(tables)
Python

Get or create object in python with psycopg postgresql

<p>The code you provided is a Python function named <code>get_or_create_obj</code> that is designed to interact with a database. This function takes two arguments: <code>data</code>, which is a dictionary representing the …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def get_or_create_obj(data,db_table):
    columns = ', '.join(data.keys())
    values = ', '.join(['%s' for _ in data])
    query = "SELECT * FROM your_table WHERE "
    params = []
    for key, value in data.items():
        query += f"{key} = %s AND "
        params.append(value)

    # Remove the trailing "AND " from the query
    query = query[:-4]
    # Execute the SQL query with the dynamically generated conditions
    cursor.execute(query, params)
    # Fetch the result
    result = cursor.fetchone()
    if result is None:
        insert_query = f"INSERT INTO {db_table} ({columns}) VALUES ({values}) ON CONFLICT DO NOTHING"
        # Execute the SQL query
        cursor.execute(insert_query, list(data.values()))
        # Commit the transaction
        connection.commit()