Django mptt, category and subcategory system - Category has no field named 'parent'

StackOverflow https://stackoverflow.com/questions/12348911

  •  01-07-2021
  •  | 
  •  

I would like created category and subcategory system using django mptt. My try:

from django.db import models
import mptt


class Category(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey('self', null=True, blank=True, related_name='children')

mptt.register(Category, order_insertion_by=['name'])

class Post(models.Model):
    title = models.CharField(max_length=255)
    text = models.TextField()
    category = models.ManyToManyField(Category)

My admin.py

from django.contrib import admin
from xxxx.xxx.models import *
from mptt.admin import MPTTModelAdmin

admin.site.register(Category, MPTTModelAdmin)
admin.site.register(Post)

My error:

Category has no field named 'parent'

有帮助吗?

解决方案

Django-mptt requires field with name parent with ForeignKey('self')

http://django-mptt.github.com/django-mptt/models.html#setting-up-a-django-model-for-mptt

You can overwrite that with:

class Category(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by=['name']
        parent_attr = 'category'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top