Как отфильтровать модель по foreignkey в админ-формах django?
Я использую django 3.2 У меня есть эти модели. При добавлении элемента в базу данных через админку django я хотел бы иметь возможность после выбора элемента Disciplina (дисциплина), когда я выбираю assunto (предмет), assunto должен быть отфильтрован по предметам дисциплины, выбранной выше. Как это сделать на чистом django (без javascript)?
from django.db import models
# Create your models here.
class Base(models.Model):
criacao = models.DateTimeField(auto_now_add=True)
atualizacao = models.DateTimeField(auto_now=True)
ativo = models.BooleanField(default=True)
class Meta:
abstract = True
class Disciplina(Base):
ORIGEM_CHOICES = [
('PT', 'Exame Nacional Português'),
('BR', 'ENEM Brasil'),
('SUPERIOR', 'Nível Superior'),
]
nome = models.CharField(max_length=100, unique=True)
origem = models.CharField(max_length=8, choices=ORIGEM_CHOICES)
def __str__(self):
return f"{self.nome} ({self.get_origem_display()})"
class Assunto(Base):
nome = models.CharField(max_length=100)
disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE, related_name='assuntos')
def __str__(self):
return f"{self.nome} ({self.disciplina.nome})"
class Questao(Base):
disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE)
assunto = models.ForeignKey(Assunto, on_delete=models.CASCADE)
latex_text = models.TextField(blank = True, null=True) # Novo campo para texto em LaTeX
math_jax = models.TextField(blank = True, null = True)
gabarito = models.CharField(max_length = 200)
dificuldade = models.CharField(max_length = 10, choices=[
('FACIL', 'Fácil'),
('MEDIO', 'Médio'),
('DIFICIL', 'Difícil'),
])
imagem = models.BooleanField(default = False)
link_imagem = models.URLField(blank =True, null=True)
link_bucket = models.URLField(blank = True, null=True)
def __str__(self):
return self.latex_text
admin.py
from django.contrib import admin
from .models import Disciplina, Assunto, Questao
@admin.register(Disciplina)
class DisciplinaAdmin(admin.ModelAdmin):
list_display = ('nome', 'origem')
search_fields = ('nome',)
ordering = ('nome',)
@admin.register(Assunto)
class AssuntoAdmin(admin.ModelAdmin):
list_display = ('nome', 'disciplina_nome')
search_fields = ('nome',)
ordering = ('nome',)
def disciplina_nome(self, obj):
return obj.disciplina.nome
disciplina_nome.short_description = 'Disciplina'
@admin.register(Questao)
class QuestaoAdmin(admin.ModelAdmin):
list_display = ('disciplina_nome', 'assunto_nome', 'latex_text', 'gabarito', 'dificuldade', 'imagem', 'link_imagem')
search_fields = ('latex_text', 'gabarito')
ordering = ('disciplina', 'assunto')
def disciplina_nome(self, obj):
return obj.disciplina.nome
disciplina_nome.short_description = 'Disciplina'
def assunto_nome(self, obj):
return obj.assunto.nome
assunto_nome.short_description = 'Assunto'