Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango, simple way to query one to many relationships?
    primarykey
    data
    text
    <p>So I want to return a dict in javascript of two tables a Category table and a Sub_category table with category = models.ForeignKey(Category). The dictionary so be 'Category1': 'Sub_cat1, Sub_cat2, ...'. I did the following code, but it seems very inefficient, so could you guys help me find another way to do this?</p> <p>Thanks!</p> <pre><code>from models import Sub_category, Category # Extra unnecessary query? def get_json_sub_categories(category): return get_json(Sub_category.objects.filter(category_id=Category.objects.filter(name=category).values('pk')[0]['pk']).values('name')) </code></pre> <p>Added: The dictionary should contain all categories and their respective sub categories. I could probably create a loop or something and call a query for each Category but that's a lot of queries. Is there one query that could get me all the Categories and their respective sub categories in a dictionary style?</p> <p>I did this instead:</p> <pre><code>from models import Sub_category, Category import json def get_sub_categories(): return Sub_category.objects.all().values('name', 'category__name') def get_dict_sub_categories(): sub_dict = {} sub_queryset = get_sub_categories() for x in sub_queryset: if x['category__name'] not in sub_dict: sub_dict[x['category__name']] = [x['name']] else: sub_dict[x['category__name']].append(x['name']) return sub_dict def get_json_sub_categories(): return json.dumps(get_dict_sub_categories()) </code></pre> <p>Anything more efficient/faster? Does my code look okay? I'm also assuming this is done with only one query. Is this true?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload