Django

Django

Explore django code snippets and tutorials

Django

Django insert large queryset into m2m

Django insert large queryset into m2m

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.db import transaction

# Retrieve the book instance
book = Book.objects.get(id=1)

# Retrieve the large queryset of authors
large_authors_qs = Author.objects.filter(name__startswith='J')

# Define the chunk size
CHUNK_SIZE = 1000

# Add authors in chunks
with transaction.atomic():
    for i in range(0, large_authors_qs.count(), CHUNK_SIZE):
        chunk = large_authors_qs[i:i + CHUNK_SIZE]
        book.authors.add(*chunk)
Django

Django run sql query to other db

Django run sql query to other db

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.db import connections

def dictfetchall(cursor):
    """Return all rows from a cursor as a list of dicts"""
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

def run_raw_query_on_db(db_name,sql_query):
    # Using the cursor to run raw SQL on 'other_db'
    with connections[db_name].cursor() as cursor:
        cursor.execute(sql_query)
        results = dictfetchall(cursor)
    
    return results
Django

Django template tag iterrate object fields dynamically

Django iterrate object fields dynamically

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
import datetime
from decimal import Decimal
from django import template
from django.db import models
from django.urls import reverse,reverse_lazy, NoReverseMatch, resolve
from django.apps import apps
from django.db.models.fields.files import ImageFieldFile, FileField
from django.db.models.fields import DateTimeField
from django.utils.html import format_html
from django.utils.safestring import mark_safe
register = template.Library()


@register.simple_tag
def display_data(object):
    items = {}
    for field in object._meta.fields:
        print(type(field), field.name)
        value = getattr(object,field.name)
        if isinstance(value, Decimal):
            value = round(value,0)
        elif isinstance(value, datetime.datetime):
            format = '%Y-%m-%d %H:%M:%S'
            print(format)
            # applying strftime() to format the datetime
            string = value.strftime(format)
            value = str(string)
        elif isinstance(field, models.ForeignKey):
            related_object = value  # This is the related object
            if related_object:  # Check if the related object exists
                value = str(related_object) 
        items[field.name] = value
    return items
Django

Dynamic filter listview django

Dynamic filter list view djnago

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
from django.db.models import Q

class BaseListView(ListView):
    def get_queryset(self):
        q_objects = Q()
        queryset = super().get_queryset()
        q = self.request.GET.get('q')
        if q and q != '':
            if not q.startswith('0'):
                try:
                    id = int(q)
                except ValueError:
                    id = None
                if id:
                    queryset = queryset.filter(id=id)
                else:
                    for f in self.model._meta.get_fields():
                        # Check if the field is a ForeignKey or ManyToManyField
                        if f.is_relation and (f.many_to_one or f.one_to_one or f.many_to_many):
                            related_model = f.related_model
                            for related_field in related_model._meta.get_fields():
                                if related_field.__class__.__name__ in ['CharField', 'TextField']:
                                    field_name = f"{f.name}__{related_field.name}"
                                    q_objects |= Q(**{f"{field_name}__icontains": q})
                        elif f.__class__.__name__ in ['CharField', 'TextField']:
                            q_objects |= Q(**{f"{f.name}__icontains": q})

                    queryset = queryset.filter(q_objects)

            else:
                for f in self.model._meta.get_fields():
                    if f.is_relation and (f.many_to_one or f.one_to_one or f.many_to_many):
                        related_model = f.related_model
                        for related_field in related_model._meta.get_fields():
                            if related_field.__class__.__name__ in ['CharField', 'TextField']:
                                field_name = f"{f.name}__{related_field.name}"
                                q_objects |= Q(**{f"{field_name}__icontains": q})
                    elif f.__class__.__name__ in ['CharField', 'TextField']:
                        q_objects |= Q(**{f"{f.name}__icontains": q})
                queryset = queryset.filter(q_objects)
                
        return queryset