[PYTHON] Create and list Django models

If you are creating a table in batch and want to create a model dynamically

def create_model_class(name: str, app_label: str = "", module: str = "", options=None, fields=None):
    class Meta(object):
        pass
    if app_label:
        setattr(Meta, "app_label", app_label)
    if options is not None:
        for key, value in options.items():
            setattr(Meta, key, value)
    attrs = {"__module__": module, "Meta": Meta}
    if fields:
        attrs.update(fields)
    model = type(name, (models.Model,), attrs)
    return model

cf. https://code.djangoproject.com/wiki/DynamicModels

Example of usage

views.py


def index(request):
    app_label = "hello"
    model_name = "ItemModel"
    ops = {"db_table": "items"}
    fields = {}
    fields["id"] = models.AutoField(primary_key=True, null=False)
    fields["name"] = models.TextField(blank=True, null=True)
    modelObj = create_model_class(
        name=model_name,
        app_label=app_label,
        module=".".join([app_label, model_name]),
        options=ops,
        fields=fields
    )

    post_list = modelObj.objects.all()
    page_obj = paginate_queryset(request, post_list, 50)
    context = {
        'list': page_obj.object_list,
        'page_obj': page_obj,
    }
    return render(request, 'hello/index.html', context)

def paginate_queryset(request, queryset, count):
    paginator = Paginator(queryset, count)
    page = request.GET.get('page')
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    return page_obj

hello/index.html


{% extends 'base.html' %}
{% block content %}
  <div class="container">
      <h3 class="text-center my-5">List of Stocks </h3>
        <table class="table table-striped table-bordered">
            <thead class="thead-inverse">
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody>
              {% for item in list %}
                  <tr>
                      <td>{{item.id}}</td>
                      <td>{{item.name}}</td>
                  <tr>
              {% endfor %}
            </tbody>
        </table>
      <div>
        <nav aria-label="Page navigation">
          <ul class="pagination">
            {% if page_obj.has_previous %}
            <li class="page-item">
              <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous">
                <span aria-hidden="true">&lt;</span>
              </a>
            </li>
            {% endif %}

            {% if page_obj.number > 3 %}
            <li class="page-item">
              <a class="page-link" href="?page=1" aria-label="First">1</a>
            </li>
            {% endif %}

            {% if page_obj.number > 4 %}
            <li class="page-item"><span class="page-link" aria-hidden="true">...</span></li>
            {% endif %}

            {% for link_page in page_obj.paginator.page_range %}
            {% if link_page == page_obj.number %}
            <li class="page-item active">
              <a class="page-link" href="?page={{ link_page }}">
                {{ link_page }}
              </a>
            </li>
            {% elif link_page < page_obj.number|add:10 and link_page > page_obj.number|add:-3 %}
            <li class="page-item">
              <a class="page-link" href="?page={{ link_page }}">
                {{ link_page }}
              </a>
            </li>
            {% endif %}
            {% endfor %}

            {% if page_obj.number < page_obj.paginator.num_pages|add:-3 %}
            <li class="page-item"><span class="page-link" aria-hidden="true">...</span></li>
            {% endif %}

            {% if page_obj.number < page_obj.paginator.num_pages|add:-2 %}
            <li class="page-item">
              <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}" aria-label="Last">{{ page_obj.paginator.num_pages}}</a>
            </li>
            {% endif%}

            {% if page_obj.has_next %}
            <li class="page-item">
              <a class="page-link" href="?page={{page_obj.next_page_number }}" aria-label="Next">
                <span aria-hidden="true">&gt;</span>
              </a>
            </li>
            {% endif %}
          </ul>
        </nav>
      </div>
  </div>
{% endblock %}

When executed, a list of common paging will be displayed.

Recommended Posts

Create and list Django models
Create Django Todo list
Create ToDo List [Python Django]
Models in Django
list and sum
list and numpy
Create ssh-config and create ssh-config host list acquisition command
Create initial settings and staff apps in Django
Create a Django schedule
Django --models.py and admin.py
Dynamically create tables in schema with Django, dynamically generate models
Create an API with Django
Django beginners create simple apps 3
Django beginners create simple apps 1
[Python] Create a date and time list for a specified period
Create a homepage with django
Install Python 3.7 and Django 3.0 (CentOS)
Django beginners create simple apps 2
Django installation and operation check
Create your own Django middleware
Create an authentication feature with django-allauth and CustomUser in Django
Python list and tuples and commas
Python list comprehensions and generators
Django input check and calendar input
Organize [Django] commands and roles
Django beginners create simple apps 5
Let's create a tic-tac-toe AI with Pylearn 2-Save and load models-
Create a temporary file with django as a zip file and return it
Create and deploy a Django (PTVS) app using Azure Table storage
Create custom Django commands and run them from the command line
Dig the directory and create a list of directory paths + file names
[Note] Django project creation and terminology
Difference between list () and [] in Python
Steps to create a Django project
Sort django models by specific criteria
HTTPS with Django and Let's Encrypt
Create new application use python, django
Create a file uploader with Django
Create and read messagepacks in Python
Create a LINE Bot in Django
Challenge to create time axis list report with Toggl API and Python
I've started learning Python and Django, so I'll list some helpful pages.
Deploy Django + React from scratch to GKE (4) Create cluster and container PUSH
Create a Todo app with Django ④ Implement folder and task creation functions