How to use objects.filter in django?



  • Good afternoon, I have a model here in my django Subject, and I want to make her listing in html, however every subject has as foreign key the id of the category model, as I make a variable to receive the objects. filter only from the subject that has as a 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
    



  • It is 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 filter directly:

    Example 2:

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



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2