Django继承模型中的控制对象创建流程 [英] Control object creation flow in Django inheritance models

查看:97
本文介绍了Django继承模型中的控制对象创建流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些有关继承模型和parent_link的Django文档. 假设我有以下模型:

I have been read some Django document about inheritance models and parent_link. Suppose that I have these models:

class Parent(models.Model):
    #Some field goes here! 
class Child(Parent):
    #Some field goes here! 

我对此模式有3个问题:

I have 3 questions about this pattern:

  1. 如果要创建新的子对象并将现有父对象的ID传递给该对象,该怎么办?

  1. What should I do if I want to create new child object and pass id of existing parent to that?

如果我只想创建一个新的子对象并在一段时间后为该子对象创建父对象,该怎么办?

What should I do if I want to create just new child object and after a while create parent object for that child?

OneToOneField.parent_link

为True并用于从其他混凝土继承的模型中 模型,指示此字段应用作返回到的链接 父类,而不是额外的OneToOneField 通常是通过子类隐式创建的.

When True and used in a model which inherits from another concrete model, indicates that this field should be used as the link back to the parent class, rather than the extra OneToOneField which would normally be implicitly created by subclassing.

感谢您的帮助!

更新问题 假设这些模型:

class User(AbsteractBaseUser):
    #Some field goes here! 

class Student(User):
    #Some field goes here! 

class Teacher(User):
    #Some field goes here! 

class Employee(User):
    #Some field goes here! 

  1. 是否可以创建Teacher对象并为该老师放置现有User对象的pk?
  1. Is it possible to create Teacher object and put the pk of existing User object for that teacher?

推荐答案

您无法在Django ORM中做到这一点.因为如果考虑数据库,那是可能的,但是在OOP中,这是不可能的.因此,您不应在Django ORM中使用模型继承.使用继承时,将在数据库的子对象中创建父级的外键,但是您无法控制它.您不能在创建时更改或设置它.如果从数据库的角度看,则在创建子对象时,将在数据库中创建两个对象,即,一个在父对象中,一个在子对象中.您应该能够为该子对象分配另一个父对象.但是,从OOP的角度来看,根据OOP原则,创建子级时,它将继承父级的所有属性,并且仅创建一个对象.因此,没有自由将另一个父对象分配给此孩子.

You cannot do that in Django ORM. Because if you think of database, it is possible but in OOP, it is not possible. So you should not use model inheritance in Django ORM. When you use inheritance, a foreign key to parent is created in child object in database but you cannot control it. You cannot change it or set it at the time of creation. If you see from database point of view, when you create child object, two objects are created in database i.e. one in parent and one in child. You should be able to assign another parent to this child object. But when you see OOP point of view, according to OOP principles, when a child is created, it inherits all the properties of parent and only one object is created. So do not have freedom to assign another parent object to this child.

您可以改用抽象模型.如果无法删除继承,则可以使用RAW SQL进行.否则,没有其他选择.

You can use abstract models instead. If you cannot remove inheritance, then you can do it with RAW SQL. Otherwise there is no any other option.

如果您可以删除继承,请在带有父项的子项中创建一个OnetoOneField.

If you can remove inheritance, create a OnetoOneField in child with parent.

这篇关于Django继承模型中的控制对象创建流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆