如何在 Django 中查询基于抽象类的对象? [英] How to query abstract-class-based objects in Django?

查看:34
本文介绍了如何在 Django 中查询基于抽象类的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个如下所示的抽象基类:

Let's say I have an abstract base class that looks like this:

class StellarObject(BaseModel):
  title = models.CharField(max_length=255)
  description = models.TextField()
  slug = models.SlugField(blank=True, null=True)

  class Meta:
    abstract = True

现在,假设我有两个从 StellarObject 继承的实际数据库类

Now, let's say I have two actual database classes that inherit from StellarObject

class Planet(StellarObject):
  type = models.CharField(max_length=50)
  size = models.IntegerField(max_length=10)

class Star(StellarObject):
  mass = models.IntegerField(max_length=10)

到目前为止,一切都很好.如果我想获得行星或恒星,我要做的就是:

So far, so good. If I want to get Planets or Stars, all I do is this:

Thing.objects.all() #or
Thing.objects.filter() #or count(), etc...

但是如果我想获得所有 StellarObjects 怎么办?如果我这样做:

But what if I want to get ALL StellarObjects? If I do:

StellarObject.objects.all()

它当然会返回错误,因为抽象类不是实际的数据库对象,因此无法查询.我读过的所有内容都说我需要做两个查询,一个查询行星和恒星,然后合并它们.这似乎非常低效.只有这样吗?

It of course returns an error, because an abstract class isn't an actual database object, and therefore cannot be queried. Everything I've read says I need to do two queries, one each on Planets and Stars, and then merge them. That seems horribly inefficient. Is that the only way?

推荐答案

从根本上说,这是对象和关系数据库之间不匹配的一部分.ORM 在抽象差异方面做得很好,但有时你还是会遇到它们.

At its root, this is part of the mismatch between objects and relational databases. The ORM does a great job in abstracting out the differences, but sometimes you just come up against them anyway.

基本上,你必须选择抽象继承,在这种情况下两个类之间没有数据库关系,或者多表继承,以效率为代价(额外的数据库连接)为每个保持数据库关系查询.

Basically, you have to choose between abstract inheritance, in which case there is no database relationship between the two classes, or multi-table inheritance, which keeps the database relationship at a cost of efficiency (an extra database join) for each query.

这篇关于如何在 Django 中查询基于抽象类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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