How to use Objects.filter in Django?

Asked

Viewed 6,199 times

5

Good afternoon, I have a model here in my Django Subject, and I want to list it in html, but every subject has as a foreign key the model id category, how I make a variable to receive Objects.filter only from the subject whose foreign key is 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
  • It will only be for this id or it will be for example an html component like: select , raiobutton that will be chosen and tell which category you would like to see the subjects ?

1 answer

5


It’s very 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 Filtre directly:

Example 2:

assuntos_da_categoria = Assunto.objects.filter(categoria__id=1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.