相关疑难解决方法(0)

Django动态模型字段

我正在开发一个多租户应用程序,其中一些用户可以定义自己的数据字段(通过管理员)以收集表单中的其他数据并报告数据.后一位使JSONField不是一个很好的选择,所以我有以下解决方案:

class CustomDataField(models.Model):
    """
    Abstract specification for arbitrary data fields.
    Not used for holding data itself, but metadata about the fields.
    """
    site = models.ForeignKey(Site, default=settings.SITE_ID)
    name = models.CharField(max_length=64)

    class Meta:
        abstract = True

class CustomDataValue(models.Model):
    """
    Abstract specification for arbitrary data.
    """
    value = models.CharField(max_length=1024)

    class Meta:
        abstract = True
Run Code Online (Sandbox Code Playgroud)

请注意CustomDataField如何具有ForeignKey to Site - 每个站点将具有一组不同的自定义数据字段,但使用相同的数据库.然后,各种具体数据字段可以定义为:

class UserCustomDataField(CustomDataField):
    pass

class UserCustomDataValue(CustomDataValue):
    custom_field = models.ForeignKey(UserCustomDataField)
    user = models.ForeignKey(User, related_name='custom_data')

    class Meta:
        unique_together=(('user','custom_field'),)
Run Code Online (Sandbox Code Playgroud)

这导致以下用途:

custom_field = UserCustomDataField.objects.create(name='zodiac', site=my_site) #probably created …
Run Code Online (Sandbox Code Playgroud)

python django dynamic django-models django-custom-manager

156
推荐指数
2
解决办法
6万
查看次数

在Python中覆盖对象的复制/深度复制操作的正确方法是什么?

所以只是为了建立,我觉得我理解复制模块中的copyvs 之间的区别deepcopy,我已经使用过copy.copy并且copy.deepcopy成功之前,但这是我第一次真正去重载__copy____deepcopy__方法.我已经围绕谷歌搜索,并通过看内置的Python模块查找的实例__copy____deepcopy__功能(例如sets.py,decimal.pyfractions.py),但我仍然肯定不是100%我已经得到了它的权利.

这是我的情景:

我有一个配置对象,它主要由简单属性组成(尽管它可能包含其他非基本对象的列表).最初,我将使用一组默认值来实例化一个配置对象.此配置将切换到多个其他对象(以确保所有对象以相同的配置启动).然而,一旦用户交互开始,每个对象将需要能够独立地调整配置而不影响彼此的配置(对我来说,我需要使用我的初始配置的深度复制来处理).

这是一个示例对象:

class ChartConfig(object):

    def __init__(self):

        #Drawing properties (Booleans/strings)
        self.antialiased = None
        self.plot_style = None
        self.plot_title = None
        self.autoscale = None

        #X axis properties (strings/ints)
        self.xaxis_title = None
        self.xaxis_tick_rotation = None
        self.xaxis_tick_align = None

        #Y axis properties (strings/ints)
        self.yaxis_title = None
        self.yaxis_tick_rotation = None
        self.yaxis_tick_align = None

        #A list of non-primitive objects
        self.trace_configs = [] …
Run Code Online (Sandbox Code Playgroud)

python python-internals

82
推荐指数
5
解决办法
5万
查看次数