Django tree modeling

被刻印的时光 ゝ 提交于 2020-01-02 05:48:09

问题


I am a completely lost newbie trying to figure out how to make my hard-coded list of links dynamically generated, not only as a noob exercise in learning Django but also so the data can be edited via admin. The important thing is that it looks the exact same when generated via the db as it does now in its hard-coded state.

The main content here needs to be represented by models:

http://www.drugpolicyreformmovement.com/directory

I think that I would first make a 'Category' table of category headings, then make a 'link' table of links with a ForeignKey relationship back to Category. I think that in the template I would use the 'ifchanged' template tag in concert with (nested?) for loops to iterate through each heading in turn, displaying each heading's child records.

Where this gets complicated is under the 'Research & Education' heading where a child record has its own child record. Potentially, esp. when I reuse this code for other projects, I would need to accommodate an arbitrary number of child levels.

I have spent two days looking through the docs and answers here and I still don't have a clear enough picture of what this would look like in models, views, or templates.

For instance, how do you traverse 'down' the child levels in the template to see if an element has children? How do you do all this w/o hitting the db a thousand times per view?


回答1:


What you do is: use django-mptt.

This is pretty much the canonical solution to storing a tree of nodes in the database and retrieving it efficiently with minimal db access. It includes some useful template tags that should help you output things how you want them.




回答2:


I would highly discourage using django-mptt for couple of reasons.

  1. You can very easily corrupt your data by simply using raw inserts.
  2. Inserting/Moving/Deleting one item results in update of whole tree. It can be slow on large trees.

It's much better to use native Postgres field ltree. There are some downsides though. It's Postres only and there. No django native libraries maintained and you have to create Postgres extension yourself. Otherwise you'll get an error type "ltree" does not exist. There's and easy fix: CREATE EXTENSION ltree;

This django-tree repo seems to work but it officially doesn't support Django 2.0



来源:https://stackoverflow.com/questions/9677681/django-tree-modeling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!