我想以编程方式向Django模型添加属性.在类创建时(定义模型类的时间).在运行时之后,模型不会改变.例如,假设我想定义一个Car模型类,并希望在price给定货币列表的情况下为每种货币添加一个属性(数据库列).(这个货币列表应该被视为一个不会改变运行时的常量.我不想要这些价格的相关模型.)
最好的方法是什么?
我有一种我认为会起作用的方法,但它并不完全正确.这就是我尝试使用上面的汽车示例的方法:
from django.db import models
class Car(models.Model):
name = models.CharField(max_length=50)
currencies = ['EUR', 'USD']
for currency in currencies:
Car.add_to_class('price_%s' % currency.lower(), models.IntegerField())
Run Code Online (Sandbox Code Playgroud)
这看起来似乎很有效:
$ ./manage.py syncdb
Creating table shop_car
$ ./manage.py dbshell
shop=# \d shop_car
Table "public.shop_car"
Column | Type | Modifiers
-----------+-----------------------+-------------------------------------------------------
id | integer | not null default nextval('shop_car_id_seq'::regclass)
name | character varying(50) | not null
price_eur | integer | not null
price_usd | integer | not null
Indexes:
"shop_car_pkey" PRIMARY KEY, …Run Code Online (Sandbox Code Playgroud) 我想将事件存储在我正在讨论的Web应用程序中,我对每种方法的利弊都非常不确定 - 广泛使用继承或以更适度的方式使用继承.
例:
class Event(models.Model):
moment = models.DateTimeField()
class UserEvent(Event):
user = models.ForeignKey(User)
class Meta:
abstract = True
class UserRegistrationEvent(UserEvent):
pass # Nothing to add really, the name of the class indicates it's type
class UserCancellationEvent(UserEvent):
reason = models.CharField()
Run Code Online (Sandbox Code Playgroud)
感觉就像我正在疯狂地创建数据库表.它需要很多连接来选择出来并且可能使查询复杂化.但我认为它的设计感觉很好.
使用只有更多字段的"更平坦"模型会更合理吗?
class Event(models.Model):
moment = models.DateTimeField()
user = models.ForeignKey(User, blank=True, null=True)
type = models.CharField() # 'Registration', 'Cancellation' ...
reason = models.CharField(blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)
感谢您对此的评论,任何人.
菲利普