gpt4 book ai didi

python - 如何使用装饰器或工厂从抽象类生成 Django 模型类?

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:06 24 4
gpt4 key购买 nike

对于一些项目,我们使用 EAV 的一个非常简单的变体。我们不需要对数据集进行过滤和查询。我们查看了django-eaveav-django ,它们不适合我们的项目,主要是因为我们不想使用GenericForeignKey。

我们现在正在研究的基本设置是这样的(省略了该问题不需要的字段,以专注于当前的问题):

# In the EAV app

class Attribute(models.Model):
name = models.CharField(max-Length=100, unique=True)


class BaseValue(models.Model):
value = models.TextField(null=False, blank=True)
attribute = models.ForeignKey(Attribute)

class Meta:
abstract = True

在使用属性的应用程序中,我们可以这样做:

# Locations with attributes

class Location(models.Model):
name = models.CharField(max_length=100, unique=True)


class LocationValue(BaseValue):
object = models.ForeignKey(Location)

这很好地达到了目的,但如果我们能够生成 LocationValue 类,那就太好了。所以我们想做但无法开始工作的是:

选项1,装饰器

# Locations with attributes

@has_attrs
class Location(models.Model):
name = models.CharField(max-Length=100, unique=True)

# The `has_attrs` decorator should generate the LocationValue class

选项 2,发电机/工厂

# Locations with attributes

class Location(models.Model):
name = models.CharField(max-Length=100, unique=True)


LocationValue = value_class_for(Location)
# The function `value_class_for` should generate the LocationValue class

重要的是,LocationValue 类与 Location 属于同一应用程序的一部分。这样做的原因是我们希望数据库模型即使对于那些直接查看它的人(而不是通过 Django 抽象层)也是可以理解的。

此外,将会有多个应用程序使用此功能,因此最终我们可能会有一个位置应用程序(Location、LocationValue)、一个纪念碑应用程序(Monument、MonumentValue)等等。

我的问题:

  1. 是否可以将 LocationValue 类的生成委托(delegate)给 models.Model 装饰器或工厂函数?
  2. 可用解决方案的优点/缺点是什么(如果有)?

感谢您分享您的知识!

最佳答案

实现这一点的 Pythonic 方法是使用 metaclass ,在第一次创建类时调用。因此,您可以控制类的创建,还可以创建其他类(将其视为类的某种“工厂”)。在设置模型类时,Django 也充分利用了这种“魔力”。您可能想看看Django's ModelBase metaclass它创建 Model 类(此外,您可能需要对其进行子类化以集成您想要的功能)。

关于python - 如何使用装饰器或工厂从抽象类生成 Django 模型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28741994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com