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

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

问题描述

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

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

class Meta:
abstract = True

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

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

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

到目前为止,很好。如果我想获得行星或星星,我所做的就是这样:

  Thing.objects.all()#or 
Thing.objects.filter()#or count()等...

但是什么如果我想得到所有的StellarObjects?如果我这样做:

  StellarObject.objects.all()

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

解决方案

在根目录下,这是对象和关系数据库之间不匹配的一部分。 ORM在提取差异方面做得非常出色,但有时候您只会反对他们。



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


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

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...

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?

解决方案

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天全站免登陆