LoginSignup
1
3

More than 3 years have passed since last update.

Django モデルの作成と一覧表示

Last updated at Posted at 2020-08-16

テーブルをバッチで作ったりしていてモデルを動的に作りたい場合

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

使い方の例

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 %}

実行するとよくあるページングの一覧が表示されます。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3