Home > Enterprise >  Django tabularInline 'categories.Category_children_ids' has more than one ForeignKey to &#
Django tabularInline 'categories.Category_children_ids' has more than one ForeignKey to &#

Time:09-20

I'm want to create nested categories, model work fine.

class Category(models.Model):
    category_name = models.CharField(max_length=100)
    children_ids = models.ManyToManyField(
        "Category", blank=True, related_name="categories"
    )
    ...etc

but, when i add inline for admin panel

class ChildrensInline(admin.TabularInline):
    model = Category.children_ids.through

compiler shows me error: 'categories.Category_children_ids' has more than one ForeignKey to 'categories.Category'. You must specify a 'fk_name' attribute.

I also try fk_name='categories', and columns name inside Category_children_ids table, but it not work

CodePudding user response:

Set fk_name='from_category or fk_name='to_category', depending on your needs:

class ChildrensInline(admin.TabularInline):
    model = Category.children_ids.through
    fk_name='from_category' # or: 'to_category'

Generally, a quick way to figure such things out is to (transiently) place a simple print(model.__dict__) pretty much anywhere in your code, here e.g. right after the second line. Then all fields of model will be shown in the console output.

  • Related