开发者

Django, simple way to query one to many relationships?

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?

Thanks!

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

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?

I did this instead:

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()开发者_JS百科
    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())

Anything more efficient/faster? Does my code look okay? I'm also assuming this is done with only one query. Is this true?


Sub_category.objects.filter(category__name=category).values('name')


So you're implementing a hierarchy in your database? I just started working on the same thing, only a user hierarchy. hierarchies are, as you seem to have realized, inefficient to model with a simple foreign key. Their is another way of modelling the data called "modified pre-order traversal tree" (MPTT) that is much more efficient. See django-mptt for an implementation prebuilt to django.

You can call a query on a mptt model to get all the nodes in one query, but you may need to loop over all the nodes, and build the dictionary yourself. Each node has parent and children relations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜