您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Django中创建动态模型字段

在Django中创建动态模型字段

有几种方法

如果必须允许站点用户/管理员直接定义其数据,我相信其他人将向你展示如何执行上述前两种方法。第三种方法是你要的,更疯狂的是,我将向你展示如何做。我不建议在几乎所有情况下都使用它,但有时它是合适的。

动态模型

一旦知道要做什么,这就相对简单了。你需要:

1.存储模型定义

这取决于你。我想你将拥有一个模型,CustomCarModelCustomField用户/管理员定义和存储所需字段的名称和类型。你不必直接镜像Django字段,可以创建自己的类型,以便用户更好地理解。

forms.ModelForm与内联表单集一起使用可让用户构建其自定义类。

2.抽象模型

同样,这很简单,只需为所有动态模型创建具有公共字段/方法的基本模型即可。使该模型抽象。

3.建立动态模型

定义一个函数,该函数接收所需的信息(可能是#1类的实例)并生成一个模型类。这是一个基本示例:

from django.db.models.loading import cache
from django.db import models


def get_custom_car_model(car_model_deFinition):
  """ Create a custom (dynamic) model class based on the given deFinition.
  """
  # What's the name of your app?
  _app_label = 'myapp'

  # you need to come up with a unique table name
  _db_table = 'dynamic_car_%d' % car_model_deFinition.pk

  # you need to come up with a unique model name (used in model caching)
  _model_name = "DynamicCar%d" % car_model_deFinition.pk

  # Remove any exist model deFinition from Django's cache
  try:
    del cache.app_models[_app_label][_model_name.lower()]
  except KeyError:
    pass

  # We'll build the class attributes here
  attrs = {}

  # Store a link to the deFinition for convenience
  attrs['car_model_deFinition'] = car_model_deFinition

  # Create the relevant Meta information
  class Meta:
      app_label = _app_label
      db_table = _db_table
      managed = False
      verbose_name = 'Dynamic Car %s' % car_model_deFinition
      verbose_name_plural = 'Dynamic Cars for %s' % car_model_deFinition
      ordering = ('my_field',)
  attrs['__module__'] = 'path.to.your.apps.module'
  attrs['Meta'] = Meta

  # All of that was just getting the class ready, here is the magic
  # Build your model by adding django database Field subclasses to the attrs dict
  # What this looks like depends on how you store the users's deFinitions
  # For Now, I'll just make them all CharFields
  for field in car_model_deFinition.fields.all():
    attrs[field.name] = models.CharField(max_length=50, db_index=True)

  # Create the new model class
  model_class = type(_model_name, (CustomCarModelBase,), attrs)

  return model_class

4.更新数据库表的代码

上面的代码将为你生成一个动态模型,但不会创建数据库表。我建议使用South进行表操作。这里有几个功能,你可以将它们连接到保存前/保存后信号:

import logging
from south.db import db
from django.db import connection

def create_db_table(model_class):
  """ Takes a Django model class and create a database table, if necessary.
  """
  table_name = model_class._Meta.db_table
  if (connection.introspection.table_name_converter(table_name)
                    not in connection.introspection.table_names()):
    fields = [(f.name, f) for f in model_class._Meta.fields]
    db.create_table(table_name, fields)
    logging.debug("Creating table '%s'" % table_name)

def add_necessary_db_columns(model_class):
  """ Creates new table or relevant columns as necessary based on the model_class.
    No columns or data are renamed or removed.
    XXX: May need tweaking if db_column != field.name
  """
  # Create table if missing
  create_db_table(model_class)

  # Add field columns if missing
  table_name = model_class._Meta.db_table
  fields = [(f.column, f) for f in model_class._Meta.fields]
  db_column_names = [row[0] for row in connection.introspection.get_table_description(connection.cursor(), table_name)]

  for column_name, field in fields:
    if column_name not in db_column_names:
      logging.debug("Adding field '%s' to table '%s'" % (column_name, table_name))
      db.add_column(table_name, column_name, field)

在那里,你拥有了!你可以调用get_custom_car_model()传递Django模型,该模型可用于执行常规django查询

CarModel = get_custom_car_model(my_deFinition)
CarModel.objects.all()

问题

总结

如果你对增加的复杂性和问题感到满意,请尽情享受!它运行着,由于Django和Python的灵活性,它可以按预期运行。你可以将模型输入Django ModelForm,让用户编辑其实例,并直接使用数据库的字段执行查询。如果上面没有什么你不了解的地方,最好不要采用这种方法(我故意不解释某些概念对初学者的意义)。把事情简单化!

我确实不认为有很多人需要这样做,但是我自己使用了它,因为我们表中有很多数据,并且确实非常需要让用户自定义列,而这些列很少更改。

Go 2022/1/1 18:24:35 有293人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶