Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda