简体   繁体   中英

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 is a bundled application which has a model called '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.

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:

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 .

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.

You can simply subclass Plan and add whatever fields / methods you want:

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

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文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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