【问题标题】:django models inheritance can't save when parent models is a treebeard当父模型是树胡子时,django模型继承无法保存
【发布时间】:2014-05-25 08:58:18
【问题描述】:

我有 2 个这样的模型:

class User(MP_Node):
    login = models.CharField(max_length=32, unique=True)
    password = models.CharField(max_length=128)


class Parent(User):
    fname = models.CharField(max_length=32)
    fmobileno = models.CharField(max_length=16)
    foccupation = models.CharField(max_length=16)
    fannual_income = models.FloatField()

现在我像这样保存一个新的父级:

parent = Parent()            
        user = User.objects.get(login='root')
        parent.user_ptr = user.add_child()
        parent.login = registration_form.cleaned_data.get('login')
        parent.password = registration_form.cleaned_data.get('password')
        parent.password = hashlib.md5(parent.password.encode('utf-8')).hexdigest()

        parent.fname =registration_form.cleaned_data.get('fname')
        parent.fmobileno =registration_form.cleaned_data.get('fmobileno')
        parent.foccupation =registration_form.cleaned_data.get('foccupation')
        parent.fannual_income =registration_form.cleaned_data.get('fannual_income')

但我得到错误 Column 'depth' cannot be null 有谁知道如何将新的父级保存到数据库中?

非常感谢!

【问题讨论】:

    标签: django


    【解决方案1】:

    我已经解决了 用这个很简单

    u = user.add_child()
    parent = Parent(user_ptr_id=u.pk)  
    parent.__dict__.update(u.__dict__)
    parent.save()
    

    从这里引用 Django model inheritance: create sub-instance of existing instance (downcast)?

    【讨论】:

      猜你喜欢
      • 2011-01-13
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多