[英]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.