如何修改Django模型? [英] How to modify a Django model?
问题描述
如果我想更改例如Django的网站模块:
from django.contrib.sites.models import Site
/ pre>
我如何在我的项目中这样做?或者我要做什么来更改或添加一些代码?
或者我只是创建一个新的模型?
解决方案
您可以通过继承添加字段
如果您仍然需要保留对原始站点的引用对象/行,您可以使用多表继承
from django.contrib.sites.models import Site
class MySite(Site) :
new_field = models.CharField(...)
def new_method(self):
#做一些新的
这允许您定期的
站点
对象,可以通过MySite
模型,在这种情况下,你可以例如通过site.mysite
访问额外的字段和方法,例如site.mysite.new_field
。
通过模型继承,您不能更改祖先字段
通过继承,您无法隐藏祖先字段,因为如果您覆盖任何祖先模型中的任何模型字段,Django将引发FieldError 。
而且我会因此,如果您更新Django,您可能会遇到与网站模型的模式冲突。
所以这里是我会做的如果我想存储祖先模型允许的更多信息:
class SiteLongName(Site):
long_name = models .CharField(max_length = 60)
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?
解决方案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 yourMySite
model, in which case you can e.g. access the extra fields and methods throughsite.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)
这篇关于如何修改Django模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!