python – How to join Django?

Question:

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;

Models:

Test, Questionnaire, Discipline

Answer:

Django queries 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 for a customer. If you want to filter an attribute of the related object, you can do: categories = CategoryCustomer.objects.filter(customer__customer_type='legal_person')

There are other ways, but the basics is this.

Scroll to Top