Skip to content

Instantly share code, notes, and snippets.

@HackerWilson
Last active June 29, 2016 20:10
Show Gist options
  • Save HackerWilson/d425ed21d008f02ced60 to your computer and use it in GitHub Desktop.
Save HackerWilson/d425ed21d008f02ced60 to your computer and use it in GitHub Desktop.
Django create mptt groups in two ways.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
方法二:mptt自有的方法见http://django-mptt.github.io/django-mptt/models.html#registration-of-existing-models
'''
import mptt
from django.contrib.auth.models import Group
mptt.fields.TreeForeignKey(Group, blank=True, null=True).contribute_to_class(Group, 'parent')
mptt.register(Group, order_insertion_by=['name'])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
方法一
'''
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from .models import UserGroup
# Django Admin Site中以层级结构显示
admin.site.register(UserGroup, MPTTModelAdmin)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
方法一
'''
from mptt.models import MPTTModel, TreeForeignKey
from mptt.managers import TreeManager
from django.db import models
from django.contrib.auth.models import Group, GroupManager
class UserGroup(MPTTModel, Group):
some_fields = models.CharField('Any field you want to add.', max_length=100)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
objects = GroupManager()
objects = TreeManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment