简体   繁体   English

如何通过扩展将额外的字段添加到django模型中?

[英]How to add extra fields to a django model by extending it?

I am developing a django application using Pinax Stripe( https://github.com/pinax/pinax-stripe ). 我正在使用Pinax Stripe开发一个django应用程序( https://github.com/pinax/pinax-stripe )。 Pinax stripe is a bundled application which has a model called 'Plans'. Pinax条带是一个捆绑的应用程序,它有一个名为'Plans'的模型。 Now in my application, I want to add some extra fields to the model 'Plans' in my application BUT without modifying the original pinax stripe application. 现在在我的应用程序中,我想在我的应用程序BUT中为模型'Plans'添加一些额外的字段,而不修改原始的pinax条带应用程序。

Something like this: 像这样的东西:

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

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

Is there any way I can do it and then register it with admin so i can add data to those fields in admin panel? 有什么方法我可以做到然后用管理员注册它所以我可以添加数据到管理面板中的这些字段?

You can inherit the Plan models and add your own attributes: 您可以继承Plan模型并添加自己的属性:

from pinax-stripe.models import Plan

class MyPlan(Plan):
    # add your attributes
    pass

This works like normal inheritance in python, plus your custom attributes are migrated when you run a migration because the original pinax Plan is a subclass of models.Model . 这类似于python中的普通继承,并且在运行迁移时会迁移自定义属性,因为原始pinax Planmodels.Model的子类。

However, be careful to not use attribute names that already exist in the pinax Plan model, since your new model will automatically take all the attibutes from Plan and Django cannot write migrations for duplicate fields. 但是,请注意不要使用pinax Plan模型中已存在的属性名称,因为新模型将自动从Plan获取所有属性,而Django无法为重复字段编写迁移。

You can simply subclass Plan and add whatever fields / methods you want: 您可以简单地子类化Plan并添加您想要的任何字段/方法:

from pinax-stripe.models import Plan

class UserProfile(Plan):
    #write the extra fields here

I'd recommend you, use the OneToOne relationship like Django docs recommend to use in the User model 我推荐你,使用像Django文档建议在用户模型中使用的OneToOne关系

from pinax-stripe.models import Plan

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM