我正在尝试在创建游戏时为游戏动态创建表格。此表将包含有关玩游戏的用户的详细信息。我不知道如何创建动态模型,因此遵循本教程:https://code.djangoproject.com/wiki/DynamicModels。它可能很旧,因为我的Django版本是1.7.1,我不确定。
我的相关代码示例如下:
def addgame(request):
...
name = request.POST.get('name','')
#declare the field types in the table
fields = { 'player' : models.ForeignKey(User),'registration_date' : models.DateField(auto_now=False,auto_now_add=False),
'highest_score' : models.PositiveIntegerField(null=True,blank=True), 'most_recent_score' : models.PositiveIntegerField(null=True,blank=True)
}
#call create_gamemodel view to create the table for the game being added.
model = create_gamemodel(name,fields)
...
def create_gamemodel(name, fields=None, module=''):
class Meta:
# Using type('Meta', ...) gives a dictproxy error during model creation
pass
# Set up a dictionary to simulate declarations within a class
attrs = {'__module__': module, 'Meta': Meta}
# Add in any fields that were provided
if fields:
attrs.update(fields)
# Create the class, which automatically triggers ModelBase processing
model = type(name, (models.Model,), attrs)
return model
错误跟踪如下:
Traceback:
File "/home/mukhera3/djangoenv/lib/python3.2/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mukhera3/Desktop/game_store/wsdProject/gamestore/views.py" in addgame
146. model = create_gamemodel(name,fields)
File "/home/mukhera3/Desktop/game_store/wsdProject/gamestore/views.py" in create_gamemodel
183. model = type(name, (models.Model,), attrs)
File "/home/mukhera3/djangoenv/lib/python3.2/site-packages/django/db/models/base.py" in __new__
109. model_module = sys.modules[new_class.__module__]
Exception Type: KeyError at /addgame/
Exception Value: ''
显然这些线路有问题:
model = create_gamemodel(name,fields) (in addgame(request) view)
model = type(name, (models.Model,), attrs) (in create_gamemodel view)
我不太明白问题所在,也不确定这是否是创建动态模型的正确方法。请帮忙!