在 Django 中获取继承的模型对象 [英] Fetching inherited model objects in django

查看:29
本文介绍了在 Django 中获取继承的模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下模型的 django 应用程序:

I have a django application with the following model:

Object A 是一个从 Model 扩展而来的简单对象,有几个字段,假设一个特定的对象是一个名为 "NAME" 的 char 字段和一个 Integer 字段称为订单".A 是抽象的,意味着数据库中没有 A 对象,而是......

Object A is a simple object extending from Model with a few fields, and let's say, a particular one is a char field called "NAME" and an Integer field called "ORDER". A is abstract, meaning there are no A objects in the database, but instead...

对象BCA 的特化,这意味着它们继承自A 并添加了一些其他的领域.

Objects B and C are specializations of A, meaning they inherit from A and they add some other fields.

现在假设我需要字段 NAME 以字母 "Z" 开头的所有对象,按 ORDER 字段排序,但我也希望这些对象的所有 BC 特定字段.现在我看到了两种方法:

Now suppose I need all the objects whose field NAME start with the letter "Z", ordered by the ORDER field, but I want all the B and C-specific fields too for those objects. Now I see 2 approaches:

a) 分别对 BC 对象执行查询并获取两个列表,合并它们,手动排序并使用它们.

a) Do the queries individually for B and C objects and fetch two lists, merge them, order manually and work with that.

b) 查询以 "Z" 开头的名称的 A 对象,按 "ORDER" 排序,结果查询 BC 对象带来所有剩余的数据.

b) Query A objects for names starting with "Z" ordered by "ORDER" and with the result query the B and C objects to bring all the remaining data.

这两种方法听起来效率都很低,第一种方法我必须自己订购,第二种方法我必须多次查询数据库.

Both approaches sound highly inefficient, in the first one I have to order them myself, in the second one I have to query the database multiple times.

是否有一种神奇的方式来获取所有 BC 对象,以一种方法排序?或者至少比上面提到的方法更有效?

Is there a magical way I'm missing to fetch all B and C objects, ordered in one single method? Or at least a more efficient way to do this than the both mentioned?

提前致谢!

布鲁诺

推荐答案

如果 A 可以具体化,您可以使用 select_related 在一个查询中完成所有这些.>

If A can be concrete, you can do this all in one query using select_related.

from django.db import connection
q = A.objects.filter(NAME__istartswith='z').order_by('ORDER').select_related('b', 'c')
for obj in q:
   obj = obj.b or obj.c or obj
   print repr(obj), obj.__dict__ # (to prove the subclass-specific attributes exist)
print "query count:", len(connection.queries)

这篇关于在 Django 中获取继承的模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆