Filter and Join with Django ORM

Asked

Viewed 693 times

0

I have 2 tables, one called Formsitems and another called Formstypes. Formsitems has an FK for Formstypes where the type of field that item is indicated. Using SQL I managed to make a Join between these tables like this:

SELECT formitems.id,formitems.name, formitems.classification, formitems.onchange, formitems.forms_id,
       formitems.form_types_id, formtypes.name
FROM service_request_formitems formitems
    inner join service_request_formtypes formtypes
    on formitems.forms_id = 42 and formtypes.id = formitems.form_types_id; 

I need to do the same thing, only using Django’s ORM but I’m not getting it, what I have so far on Django is the following code:

def formulario(self, request):
        itemId = 81
        item = Items.objects.get(id=itemId)
        itemForId = item.forms.id
        formsItems = FormItems.objects.filter(forms_id=itemForId).order_by('classification')

But it does not Join and returns me the field name of the table Formtypes.

I have no experience with either sql or Django’s ORM, I know the basics and I am trying to advance so any help with that I thank.

My models are :

class FormItems(models.Model):
    form_types = models.ForeignKey(
        'FormTypes', on_delete=models.SET_NULL, null=True)
    name = models.TextField(null=True)
    description = models.TextField(null=True)
    classification = models.IntegerField()
    onchange = models.TextField(null=True)

class FormTypes(models.Model):
    name = models.TextField()

1 answer

1


You can use your queries directly, but being able to use the ORM, many things are much easier.

You need to do something like this, use the "select_related" operator of the Django ORM:


def formulario(self, request):
    # ...
    FormItems.objects.select_related('form_types').filter(forms_id=itemForId).order_by('classification')

You can filter through your form types directly, like this:

FormItems.objects.select_related('form_types').filter(form_types__id=id).order_by('classification')

Browser other questions tagged

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