How to use objects.filter in django?

1

Good afternoon, I have a model here in my django Subject, and I want to make the listing of it in the html, however every subject has as foreign key the id of the model category, as I make a variable to receive the objects.filter only of the subject that has the foreign key the value 1 for example?

My view

def index(request):
    assunto_jogo = Assunto.objects.filter()
    return render(request, “index.html”)

model subject

class Assunto(models.Model):
    nome = models.CharField('Nome', unique=True, max_length=150)
    descricao = models.TextField('Descrição')
    id_categoria = models.ForeignKey(Categoria)

    def __str__(self):
       return self.nome

and category

class Categoria(models.Model):
    nome = models.CharField('Nome', unique=True, max_length=150)

    def __str__(self):
        return self.nome
    
asked by anonymous 24.11.2017 / 15:46

1 answer

1

It's quite simple, take the category and then list the subjects related to it:

Example 1:

categoria = Categoria.objects.get(id=1)
assuntos_da_categoria = categoria.assunto_set.all()

Or filter directly:

Example 2:

assuntos_da_categoria = Assunto.objects.filter(categoria__id=1)
    
24.11.2017 / 18:50