0

I have the following code that iterates the tags queryset, and for each item, creates a Department object and adds it to the departments list:

departments: List[Department] = []

tags = Tag.objects.filter(type="department")

for tag in tags:
    dept_id = tag.reference_id
    dept_name = tag.name

    parent_tag = Tag.objects.get(type="department", reference_id=tag.parent_reference_id)
    dept_parent_id = parent_tag.reference_id

    departments.append(Department(dept_id, dept_name, dept_parent_id))

However, as you can see, it is making multiple DB calls via Tag.objects.get(), which seems highly inefficient. Is there an efficient way to populate that departments list without making so many DB calls?

TIA.

2 Answers 2

1

What you need to use is "in" in your query.

check querysets

Entry.objects.filter(id__in=[1, 3, 4])
Entry.objects.filter(headline__in='abc')

so in your case you can use the the following example :

tags = Tag.objects.filter(id=some_id, type="department").values('id')
tags_list = [tag['id'] for tag in tags]
parent_tag = Tag.objects.get(id__in=tags_list, type="department")
Sign up to request clarification or add additional context in comments.

Comments

0

I have used parts of the answer from @Vanda to write the following solution, and this solves my problem.

departments: List[Department] = []

tags = Tag.objects.filter(type="department")
parents_set = {tag.parent_reference_id for tag in tags}

for tag in tags:
    dept_id = tag.reference_id
    dept_name = tag.name

    dept_parent_id = tag.parent_reference_id
    if(dept_parent_id not in parents_set):
        dept_parent_id = None

    departments.append(Department(dept_id, dept_name, dept_parent_id))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.