H
H
Heik2016-11-06 02:41:19
Django
Heik, 2016-11-06 02:41:19

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')

Then I created a new dictionary and filled it with data from the tables using "for". It turned out something like:
dict = {
        'elem1': [{
            '0': {
                'id': '100',
                'name': 'test',
                'color': 'red',
                ...
            },
            '1': {
                'id': '200',
                'name': 'test2',
                'color': 'green',
                ...
            }
        }],
        'elem2': [{
            '0': {
                'id': '20',
                'name': 'test3',
                'color': 'yellow',
                ...
            },
        }]
    }

How bad is it in terms of speed and in general?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Abdulla Mursalov, 2016-11-06
@Heik

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 question

Ask a Question

731 491 924 answers to any question