Answer the question
In order to leave comments, you need to log in
Django ORM: fetching multiple tables into a dictionary?
In general, there are two independent tables (models). I need to collect values from them and pass them to the template with one dictionary. Well, like this:
class TableA(models.Model):
field1
field2
main_img
color
...
class tableB(models.Model):
name
field1
field2
...
tableA = TableA.objects.filter(main_img=1).values('color')
tableB = TableB.objects.values('id', 'name')
dict = {
'elem1': [{
'0': {
'id': '100',
'name': 'test',
'color': 'red',
...
},
'1': {
'id': '200',
'name': 'test2',
'color': 'green',
...
}
}],
'elem2': [{
'0': {
'id': '20',
'name': 'test3',
'color': 'yellow',
...
},
}]
}
Answer the question
In order to leave comments, you need to log in
Python code is always (almost) slower than database fetching.
That is, it is more profitable to write rawSQL. But it is your responsibility to protect yourself from SQL injection.
If SQL is not enough, and there is a need to process an array of information in python (rarely, most likely you are doing something wrong), then use the ready-made itertools library, because your cycles may not be optimal. Also study the behavior of querysets, iterator(). In general, if you describe the task in more detail, you don’t have to guess.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question