django model field definition for hierarchy, GenericForm
I want to represent a model hierarchy of categories in django orm. So f.i. you could have categories such as:
TopCategory
SubCategory1
SubSubCategory
SubCategory2
This is my field definition, which points to the parent category:
class Category(models.Model)
parentcategory = models.OneToOneField('self', blank = True, null = True)
And I use a GenericForm in the view:
def detail(request, category_id):
categoryInstance = Category.objects.get(pk = category_id)
GenericForm = modelform_factory(Category)
form = GenericForm(instance = categoryInstance)
if request.method == 'POST':
form = GenericForm(request.POST, instance = categoryInstance)
if form.is_valid():
form.save()
This does work, there is only one slight pr开发者_如何学Coblem. No category should be allowed to point to itself as a parent. The form renders a dropdown where all categories are listed however.
I did try something like this in the field definition:
limit_choices_to = Q('parentcategory_id' is not id)
But that gave me an error. I could probably check and present an error message to the user, but maybe someone knows another way?
django-mptt is recommended for working with hierarchies in django.
精彩评论