【问题标题】:Creating fields on the fly in django在 django 中动态创建字段
【发布时间】:2012-07-12 19:25:40
【问题描述】:

我有两张桌子(比如 Parent 和 Child)。我希望父母和孩子使用外键相互链接。子表有两个字段,其中一个是“country_sig”。这个 country_sig 实际上是由 父表 中名为 'country' 和 'code' 的两个字段组成的。 例如:如果国家/地区为“IN”且代码为“15”,则 country_sig 为 IN.15。

现在我希望在为父表创建 django 模型期间,它应该自动创建这个字段 country_sig 派生自“国家”和“代码”,以便我可以将其引用到子表。

PS:由于父表非常大,我不想在从这两个字段派生的数据库中创建另一个字段,但我可以调整另一个表(子表)以将 country_sig 字段分为两列使用 'country' 和 'code' 但这不起作用,因为 django 不支持复合主键。

编辑: 实际上我是在美味派中实现它,我希望美味派认为它是一个真实的领域。这将解决我真正的问题。

【问题讨论】:

  • 我不确定您所说的相互引用是什么意思。是否要动态添加此组合字段以便从子表中查询?
  • 因为我在tastepie中实现它,(问题已编辑)
  • 那么你想让tasypie在父资源中输出这个组合字段吗?
  • 我正在做一些事情,其中​​涉及让美味的傻瓜假设表中存在一个真实的字段,但实际上它并不存在。是的,在父资源中输出这个组合字段和美味的馅饼。

标签: python django tastypie composite-primary-key


【解决方案1】:

也许不要使用标准的tasypie ModelResources,而是自己编写资源:

class DictWrapper(object):
    '''
    to be used as generic tastypie resource object 
    '''
    def __init__(self, initial=None):
        self.__dict__['_data'] = {}

        if hasattr(initial, 'items'):
            self.__dict__['_data'] = initial

    def __getattr__(self, name):
        return self._data.get(name, None)

    def __setattr__(self, name, value):
        self.__dict__['_data'][name] = value

    def to_dict(self):
        return self._data

class ParentResource(Resource): 
    def get_object_list(self, request):        
        ret = []
        for parent in Parent.objects.all():
            ret.append(DictWrapper({"country_sig":"{0}.{1}".format(parent.country, parent.code})))
        return return

    def obj_get_list(self, request=None, **kwargs):      
        return self.get_object_list(request)

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2011-04-12
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多