【问题标题】:Django multi table inheritance: Find and change parent modelDjango多表继承:查找和更改父模型
【发布时间】:2015-12-15 11:23:12
【问题描述】:

假设我在 django 中有以下模型结构:

class A(models.Model):  
    x = models.IntegerField()

    def copy(self):
        obj = self
        obj.pk = None
        obj.save()

        return obj

class B(A):
    y = models.IntegerField()

    def copy(self):
        # this method is what I am confused about
        new_parent = super(B, self).copy()  # not sure about this
        obj = self
        obj.pk = None
        # how to set obj's parent model to 'new_parent'
        obj.save()
        return obj

我不确定如何访问父模型的对象,以及如何使此复制方法起作用?

我已经搜索了很多,但找不到任何答案。我应该只使用一对一的关系吗?

【问题讨论】:

  • 我认为您需要对父模型对象使用外键关系

标签: python django inheritance


【解决方案1】:

如果您有一个普通的父子模型,您将获得子属性以访问父。您可以使用新的父对象更新此属性。

另外,您创建父对象的方式可能不起作用,您需要在该对象上调用方法。

所以我将孩子的copy() 方法更新为:

class B(A):

    def copy(self):
        # this method is what I am confused about
        new_parent = self.a.copy()  # change 'a' with appropriate attribute name
        obj = self
        obj.pk = None
        # set obj's parent model to 'new_parent'
        obj.a = new_parent
        obj.save()
        return obj

【讨论】:

  • 这很简单!谢谢
  • 是否有任何 django 文档更详细地解释了这一点?还有“a_ptr”和“a_ptr_id”字段。它们是干什么用的?
猜你喜欢
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 2012-09-20
  • 2010-11-08
相关资源
最近更新 更多