【问题标题】:How to add extra fields to a django model by extending it?如何通过扩展向 django 模型添加额外的字段?
【发布时间】:2016-06-13 22:23:56
【问题描述】:

我正在使用 Pinax Stripe(https://github.com/pinax/pinax-stripe) 开发一个 django 应用程序。 Pinax stripe 是一个捆绑的应用程序,它有一个名为“Plans”的模型。现在在我的应用程序中,我想在我的应用程序中向模型“计划”添加一些额外的字段,但不修改原始 pinax 条纹应用程序。

类似这样的:

    #models.py
from pinax-stripe.models import Plan

class UserProfile(models.Model):
    #write the extra fields here

有什么办法可以做到,然后向管理员注册,这样我就可以将数据添加到管理面板中的这些字段?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以继承Plan 模型并添加自己的属性:

    from pinax-stripe.models import Plan
    
    class MyPlan(Plan):
        # add your attributes
        pass
    

    这与 python 中的普通继承类似,而且您的自定义属性在您运行迁移时会被迁移,因为原始 pinax Planmodels.Model 的子类。

    但是,请注意不要使用 pinax Plan 模型中已经存在的属性名称,因为您的新模型将自动获取来自 Plan 的所有属性,并且 Django 无法为重复字段编写迁移。

    【讨论】:

    • 谢谢@Moses 既然您知道 pinax 条纹,您知道如何使用代码(可能是 webhook 或其他东西)将计划添加到我的计划中吗?
    • @Elisha512 不幸的是,我从来没有理由使用pinax-stripe,所以我真的不太了解它的工作原理。
    【解决方案2】:

    您可以简单地继承 Plan 并添加您想要的任何字段/方法:

    from pinax-stripe.models import Plan
    
    class UserProfile(Plan):
        #write the extra fields here
    

    【讨论】:

      【解决方案3】:

      我推荐你,使用OneToOne 关系like Django docs recommend to use in the User model

      from pinax-stripe.models import Plan
      
      class UserProfile(models.Model):
          plan = models.OneToOneField(Plan , on_delete=models.CASCADE)
          #write the extra fields here
      

      【讨论】:

        【解决方案4】:

        您可以从https://github.com/pinax/pinax-stripe 将 pinax 文件夹下载到您的应用中,并根据您的要求编辑 models.py 和 admin.py 文件。

        【讨论】:

          猜你喜欢
          • 2021-08-25
          • 2018-08-31
          • 2018-10-21
          • 2016-04-17
          • 1970-01-01
          • 2019-12-30
          • 1970-01-01
          • 2018-01-19
          • 1970-01-01
          相关资源
          最近更新 更多