How do I join with Django?

2

I'm trying to run this SQL using Django's ORM

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

Templates:

  

Test, Questionnaire, Discipline

    
asked by anonymous 31.10.2015 / 05:38

1 answer

1

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

CHOICE_CLIENTE = (
    ('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 get all categories from a client, 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 client. If you want to filter an attribute of the related object, you can do the following:     categories = CategoryClient.objects.filter (client__client_type = 'legal_person')

There are other ways, but the basics is this.

    
31.10.2015 / 19:33