Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

python - How to modify a Django model?

If I would like to change e.g. Django's Site module:

from django.contrib.sites.models import Site

How would I do that in my project? Do I subclass or what do I do to change or add some code to it?

Or do I just create a new model?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add a field via inheritance

If you still need to keep a reference to the original Site object/row, you can use multi-table inheritance

from django.contrib.sites.models import Site

class MySite(Site):
    new_field = models.CharField(...)

    def new_method(self):
        # do something new

This allows you to have regular Site objects, that may be extended by your MySite model, in which case you can e.g. access the extra fields and methods through site.mysite, e.g. site.mysite.new_field.

Through model inheritance, you cannot alter an ancestor field

Through inheritance you cannot hide ancestor fields, because Django will raise a FieldError if you override any model field in any ancestor model.

And I wouldn't venture and write a custom DB migration for this, because then if you update Django, you may get schema conflicts with the Site model.

So here's what I would do if I wanted to store more info that the ancestor model allows:

class SiteLongName(Site):
    long_name = models.CharField(max_length=60)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...