【发布时间】:2019-12-13 20:27:20
【问题描述】:
我现在正在尝试将一堆类合并到 django 中。
例如,我有一个 Base 类,我的所有其他类都派生自该类:
class Base:
def __init__(self, label: str = 'Base'):
self.label = label
子类的一个例子是Person 类:
from typing import Any, Dict
class Person(Base):
def __init__(self, name: str, attributes_to_options: Dict[str, Any], **kwargs):
super().__init__(**kwargs)
self.name = name
self.attributes_to_options = attributes_to_options
我会把它用作:
alex = Person(name='Alex', attributes_to_options={'age': 10, 'is_happy': True}, label='Person:Alex')
我的问题是,如何将这样的类合并到django 中? 是不是像从models.Model 继承一样简单?例如
from django.db import models
class Person(Base, models.Model):
def __init__(self, name: str, attributes_to_options: Dict[str, Any], **kwargs):
super().__init__(**kwargs)
self.name = name
self.attributes_to_options = attributes_to_options
但是我该如何为name 和attributes_to_options 两个属性指定models.CharField?
感谢您的帮助。
【问题讨论】:
-
您是否尝试过在 Person 类范围内声明
name = models.CharField(...)等?重要的是模型字段必须在继承自models.Model的类中声明。 -
你可以有一个abstract base model 来实现一些字段,比如“label”
-
我不知道你为什么要为 attributes_to_option 属性使用 CharField,因为那是一个字典。如果确实需要,则必须在保存之前将其转换为字符串。如果你使用的是 postgresql,你应该考虑使用 JSONField 而不是 CharField。
-
将字典作为参数传递几乎总是一个坏主意......字典是键/值存储而不是移动命名空间
-
@alex_lewis 将字典作为对象/命名空间传递的问题是,当您或其他任何人来调试您的代码时,您只会看到传入函数的字典,不知道是什么在其中,然后您必须在堆栈中搜寻,也许可以找到该键设置的位置或未设置的位置,我去过那里,但这并不有趣。函数的显式参数可能会稍有限制,但可以节省大量调试工作
标签: django python-3.x class subclass