1

I would like to query across 4 tables ( directions, layers, metal stack, and layers). I have the majority of the query done except for one part which I will explain further below. I need a resulting table with the columns layers, directions, stackname, width.

In sql, it would be something like:

Class stack():
    id
    stackname

Class layers():
    id
    layers

Class directions():
    id
    directions

Class List():
    directions_id= models.ForeignKey(directions)
    layers_id= models.ForeignKey(layers)
    metalstack_id= models.ForeignKey(stack)
    width


SELECT layers, directions, stackname, width
FROM List 
JOIN layers l
ON l.id = List.layers_id
JOIN directions d
ON d.id = List.directions_id
JOIN stack s
ON s.id = List.metalstack_id;

The query below gets me layers_id, directions_id, stack_id, width which values are correct. However instead of getting the id, I want to have the layers, directions and stackname value instead. I tried changing it to values("stackname","directions", "layers","pitch","space","width") but it did not work.

views.py

list= List.objects
.filter(metalstack_id__in=stackid)
.select_related('directions','layers','stackname')
.values("metalstack_id","directions_id",layers_id","width")
rellzz
  • 31
  • 3

1 Answers1

0

You can try using Django's first(), last() queryset methods according to your needs.

SomeModel.objects.filter(field_name=value).values("id", "name").first()

Full documentation: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#first

Debashis Dip
  • 91
  • 1
  • 6
  • Do you know something that allows more flexibility in querying across different tables? As you have seen, my models.py has alot of relationships between them. Possibility across 3 tables? – rellzz Jun 23 '21 at 13:52
  • you might want to look into `select_related` and `prefetch_related` – Debashis Dip Jun 23 '21 at 15:56