Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Recursive Model in Admin Add Page

I have a model called Category which is recursive. The model goes like this:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=255, blank=False)
    description = models.CharField(max_length=255, blank=False)
    sub_category = models.ForeignKey('self', blank=True, null=True, related_name='subcategory')

    def __str__(self):
        return self.name

my admin.py for category is:

from django.contrib import admin
from category.models import Category
from django import forms

class CategoryAdmin(admin.ModelAdmin):
    list_display = ['id', "name", "sub_category", 'description']
    list_filter = ["name"]
    search_fields = ["name"]
    ordering = ('sub_category',)

    class Meta:
        model = Category

admin.site.register(Category, CategoryAdmin)

When I want to add more categories to the database, I go to the admin section and do it however, suppose I need to distinguish which category is a part of its parent category how would I go about doing that? right now, I'm seeing: enter image description here

which is not quite helpful, Is there a way to perhaps have the parent category next to the subcategory? like this format:

  • [Java] Tutorials
  • [Python] Tutorials
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I was really stupid with this one, the answer was really simple, basically, I just had to edit the __str__ method in the model...

def __str__(self):
    if self.sub_category != None:
        return '[{0}] {1}'.format(self.sub_category.name, self.name)
    return self.name
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!