gpt4 book ai didi

python - 以编程方式指定 Django 模型属性

转载 作者:太空狗 更新时间:2023-10-29 22:20:30 24 4
gpt4 key购买 nike

我想以编程方式向 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())

乍一看,这似乎工作得很好:

$ ./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, btree (id)

但是当我尝试创建一辆新汽车时,它不再有效了:

>>> from shop.models import Car
>>> mycar = Car(name='VW Jetta', price_eur=100, price_usd=130)
>>> mycar
<Car: Car object>
>>> mycar.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 410, in save
self.save_base(force_insert=force_insert, force_update=force_update)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 495, in save_base
result = manager._insert(values, return_id=update_pk)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/manager.py", line 177, in _insert
return insert_query(self.model, values, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/query.py", line 1087, in insert_query
return query.execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/subqueries.py", line 320, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/util.py", line 19, in execute
return self.cursor.execute(sql, params)
ProgrammingError: column "price_eur" specified more than once
LINE 1: ...NTO "shop_car" ("name", "price_eur", "price_usd", "price_eur...
^

但显然,我的代码似乎运行了几次,导致“price_eur”属性被添加了几次。

评论:最初我使用了“在运行时”的措辞(“我想在运行时以编程方式向 Django 模型添加属性。”)。这个措辞不是最好的。我真正想要的是在“模型定义时间”或“类创建时间”添加这些字段。

最佳答案

我的解决方案由于各种原因是不好的,但它有效:

from django.db import models

currencies = ["EUR", "USD"]

class Car(models.Model):

name = models.CharField(max_length=50)

for currency in currencies:
locals()['price_%s' % currency.lower()] = models.IntegerField()

在我必须这样做的地方,我可以在类似的事情和维护包含 200 多列的表之间做出选择(我知道这有多糟糕,但我对此没有影响)。

关于python - 以编程方式指定 Django 模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2501173/

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