本文へスキップ
hdknr blog
戻る

djang-mptt: tree 構造で export する

django-mptt: Tree モデルを エクスポート

profiles/templates/profile/workgroup/tree.json:

{% load mptt_tags %}
[
{% recursetree nodes %}
{
    "id": "{{ node.id }}",   
    "code": "{{ node.code|default:''}}",
    "name": "{{ node.name }}",   
    "path": "{{ node.path }}",
    "full_name": "{{ node.full_name }}",
    "data": {},   
    "children": [{{ children }}]
}{% if node.get_next_sibling %},{% endif %}
{% endrecursetree %}
]
from django.template import engines, loader
from django.utils.safestring import mark_safe
from django.db.models import QuerySet

def render(src, request=None, engine_name="django", safe=True, **ctx):
    text = engines[engine_name].from_string(src).render(ctx, request=request)
    return safe and mark_safe(text) or text

def render_by(name, request=None, safe=True, **ctx):
    t = loader.get_template(name)
    text = t.render(ctx, request=request)
    return safe and mark_safe(text) or text

def export_trees(nodes, model_class=None, template_name=None, request=None, safe=True, **ctx):
    if not model_class and isinstance(nodes, QuerySet):
        model_class = nodes.model

    if not template_name and model_class:
        template_name = f"{model_class._meta.app_label}/{model_class._meta.model_name}/tree.json"

    if not template_name:
        return ""

    return render_by(template_name, request=request, safe=safe, nodes=nodes, **ctx)
@main.command()
@click.argument("path")
@click.pass_context
def workgroup_export(ctx, path):
    """ Workgroup Export """

    nodes = models.Workgroup.objects.all()
    print(export_trees(nodes))


前の記事
macOS: ls: .: Operation not permitted
次の記事
Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async