【问题标题】:Django model inheriting from different models, which each inherit from a single classDjango 模型继承自不同的模型,每个模型都继承自一个类
【发布时间】:2014-07-22 06:20:09
【问题描述】:

我正在使用 Django 创建一个表单。此表单的 ModelForm 建立在从基本模型继承的多个模型之上。模型的结构类似于:

class BaseModel(models.Model):
    first_name = models.CharField("First name", max_length=20)
    middle_name = models.CharField("Middle name", max_length=20)
    last_name = models.CharField("Last Name", max_length=20)
    email = models.EmailField("Email address")
    phone = models.CharField("Phone number", max_length=16)

被继承

class EmployerModel(BaseModel):
    company = models.CharField("Company", max_length=20)

和..

class AdvisorModel(BaseModel):
    department = models.CharField("Department", max_length=20)

包含在我的最高级别模型中(我的 ModelForm 中使用的模型):

class FormModel(EmployerModel, AdvisorModel):
    another_field = models.CharField(max_length=20)
    and_another_field = models.CharField(max_length=20)

#...

class FormModelForm(forms.ModelForm):

    class Meta:
        model = FormModel

我可以在制作表单时采用这种方法并避免 ORM 错误,因为我有重复的字段名称吗?有没有办法分开说; “这些字段用于‘雇主’;这些字段用于‘顾问’?”

编辑

看起来我需要使用抽象基类,但我不知道这是否解决了多重继承问题。

【问题讨论】:

    标签: python django inheritance


    【解决方案1】:

    对父模型进行抽象,我已经成功编写了具有这种定义的模型:

    class Content(ModeratedModel, NullableGenericModel, RatedModel, PicturableModel, PrivacyModel, CommentableModel):
        pass
    

    ModelForms 使用Content 作为模型工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-18
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      相关资源
      最近更新 更多