简体   繁体   English

django prefetch_related和select_related在父表上

[英]django prefetch_related and select_related on parent table

I have the following db structure: 我有以下数据库结构:

catogory
   id
   name
   parent_id

class Category(models.Model)
  name = models.CharField(max_length=400, blank=True, null=True)
  parent = models.ForeignKey("self", blank=True, null=True)

I need to fetch all categories and their parent. 我需要获取所有类别及其父类别。

If I do: 如果我做:

Category.objects.select_related("parent").filter(pk__in=[ids])

it would just return the parent of the first level. 它只会返回第一级的父级。

How can I retrieve the parents of all level with minimum db calls? 如何以最少的数据库调用来检索所有级别的父级?

My approach is to build a new non-db-model objects eg: CategorySerializer that will transfer those Category models to non db ones so the logic layer could use it 我的方法是建立一个新的非db-model对象,例如:CategorySerializer,它将把那些Category模型转移到非db-model对象,以便逻辑层可以使用它

What if you created a function that you can call recursively until there are no more parents left 如果您创建了一个可以递归调用的函数,直到没有更多的父母了该怎么办

def get_categories(ids):
    ids = list(Category.objects.select_related("parent").filter(pk__in=[ids]).values_list('parent_id', flat=True))
    if len(ids) == 0:
        return []
    else:
        return ids + get_categories(ids)

So start with this call 所以从这个电话开始

all_parent_ids = []
for category in list(Category.objects.all()):
    all_parent_ids.append(get_categories(category.parent_id))

I haven't tested this, so it may need some refinement, but I believe the idea is correct. 我尚未对此进行测试,因此可能需要一些改进,但是我认为这个想法是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django prefetch_related和select_related - Django prefetch_related and select_related Django:4 个表中的 select_related() / prefetch_related() - Django: select_related() / prefetch_related() among 4 tables 使用 django 中的 select_related 和 prefetch_related 过滤和获取 - Filter and fetch using select_related and prefetch_related in django django model select_related 或 prefetch_related 子 model - django model select_related or prefetch_related child model Django select_related vs prefetch_related在树状表中 - django select_related vs prefetch_related in tree like table Select_related(和prefetch_related)不能按预期工作吗? - Select_related (and prefetch_related) not working as intended? DRF select_related 和 prefetch_related 不起作用 - DRF select_related and prefetch_related doesn't work 无法减少 Django 中一对一关系中“select_related()”和“prefetch_related()”的“SELECT”查询 - Cannot reduce "SELECT" queries with "select_related()" and "prefetch_related()" in one-to-one relationship in Django 过滤prefetch_related和select_related结果 - filter prefetch_related and select_related results 将select_related和prefetch_related与许多参数一起使用 - using select_related and prefetch_related with many arguments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM