How to make a Join with Django?


Viewed 1,820 times


I’m trying to run this SQL, using Django’s ORM

SELECT * FROM test JOIN questionnaire q ON ( = test.questionnaire) WHERE q.discipline = 4;


Test, Questionnaire, Discipline

1 answer


The Django queries happen in a very simple way, for example:

    ('pessoa_fisica','Pessoa Física'),
    ('pessoa_juridica','Pessoa Jurídica'),
class Cliente(models.Model):
    nome = models.CharField(max_length=255)
    descricao = models.CharField(mad_length=255)
    tipo_cliente = models.CharField(max_length=15, choices=CHOICE_CLIENTE)

class CategoriasCliente(models.Model):
    descricao = models.CharField(max_length=255)
    cliente = models.ForeignKey (Cliente)

To pick up all categories from a customer, you would:

cliente = Cliente.objects.get(id=cliente_id)
# ou cliente = get_object_or_404(Cliente, id=cliente_id) (boa prática)

categorias = CategoriaCliente.objects.filter(cliente=cliente)

This would return all categories of a customer. If you want to filter an attribute of the related object, you can do: categories = Categoriacliente.objects.filter(cliente__type_client='person_legal')

There are other ways, but the basic thing is this.

Browser other questions tagged

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