如何修改 Django 模型? [英] How to modify a Django model?

查看:27
本文介绍了如何修改 Django 模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想改变,例如Django 的站点模块:

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?

推荐答案

可以通过继承添加字段

如果您仍然需要保留对原始站点对象/行的引用,您可以使用 多表继承

from django.contrib.sites.models import Site

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

    def new_method(self):
        # do something new

这允许您拥有常规的 Site 对象,这些对象可以由您的 MySite 模型扩展,在这种情况下,您可以例如通过 site.mysite 访问额外的字段和方法,例如site.mysite.new_field.

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.

通过继承你不能隐藏祖先字段,因为 如果覆盖任何祖先模型中的任何模型字段,Django 将引发 FieldError.

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

而且我不会冒险为此编写自定义数据库迁移,因为如果您更新 Django,您可能会与站点模型发生架构冲突.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆