5

How to create Postgres ltree data type for Django? and how to use it with QuerySets? (create wrapper? how?)

About lree here: http://www.postgresql.org/docs/current/static/ltree.html

About custom fields in Django here: docs.djangoproject.com/en/1.2/howto/custom-model-fields/

P.S. Also there are "Django Tree Libraries" but ltree looks better..

Milen A. Radev
  • 60,241
  • 22
  • 105
  • 110
  • 1
    What's wrong with django-mptt? I've been using it for a while (as have others here) with good results. – Dominic Rodger Nov 05 '10 at 11:12
  • 1
    django-mptt use nested set model (http://en.wikipedia.org/wiki/Nested_set_model). Yes, it's good model but it's optimized for fast read (its the best solutuon if only you generate content on your site, users mostly read than create). It's not very good if you allow users generate content and your trees are big (with every insert system will update a lot of items). Also there is interesting article http://www.davidcramer.net/code/django/6939/scaling-threaded-comments-on-django-at-disqus.html and benchmarks https://tabo.pe/projects/django-treebeard/docs/1.61/benchmarks.html – Alexander Ovchinnikov Nov 05 '10 at 20:53
  • 1
    How to store trees in database? 1. nested sets (django-mptt, django-treebeard, django-easy-tree) - good for read operations (also there are nested intervals, sorry, too complicated to explain for me and no apps for django); 2. Adjacency List (django-treebeard) - easy way if tree with not very big depth. 3. Materialized Path (django-treebeard or ltree(if use postgres)) - best way for me, because many write operations. So if will no luck with this my question, best way for me - use Materialized Path (django-treebeard). – Alexander Ovchinnikov Nov 05 '10 at 21:23
  • Regarding your comment about "ltree looks better", you might want to figure out what you would gain from an ltree (see https://stackoverflow.com/questions/59132388/postgres-materialized-path-what-are-the-benefits-of-using-ltree) – Avi Kaminetzky Dec 05 '19 at 15:54

2 Answers2

7

There is django-ltree that manages the integration for you. It also has the migrations to add the ltree extension in your database.

Mario César
  • 3,699
  • 2
  • 27
  • 42
3

You have listed two of the correct pieces. The general method for adapting a PostgreSQL data type to Django is:

  1. Create a new Python class that represents the data type.
  2. Register that data type with psycopg2 so that psycopg2 understands how adapt it to the database.

Documentation on step 2 is available at http://initd.org/psycopg/docs/advanced.html#adapting-new-types ...

Christophe
  • 2,052
  • 1
  • 19
  • 24