Django—如何在不修改的情况下扩展第三方模型

时间:2022-11-24 22:56:00

I want to add a column to a database table but I don't want to modify the 3rd party module in case I need/decide to upgrade the module in the future. Is there a way I can add this field within my code so that with new builds I don't have to add the field manually?

我想向数据库表中添加一个列,但我不想修改第三方模块,以防将来需要/决定升级该模块。有没有一种方法可以在我的代码中添加这个字段,这样我就不用手动添加新的构建了?

2 个解决方案

#1


9  

You can use ModelName.add_to_class (or .contribute_to_class), but if you have already run syncdb, then there is no way to automatically have it add the columns you need.

您可以使用ModelName。add_to_class(或.contribute_to_class),但是如果您已经运行了syncdb,那么就无法自动地让它添加所需的列。

For maintainable code, you will probably want to extend by sub-classing the desired model in your own app, and use something like south to handle the database migrations, or just use a OneToOneField, and have a related model (like UserProfile is to auth.User).

对于可维护性代码,您可能想要在自己的应用程序中对所需的模型进行子类化,并使用类似于南方的东西来处理数据库迁移,或者只使用OneToOneField,并有一个相关的模型(比如UserProfile是auth.User)。

#2


0  

Take a look to Django model inheritance and abstract classes http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance

查看Django模型继承和抽象类http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table继承

#1


9  

You can use ModelName.add_to_class (or .contribute_to_class), but if you have already run syncdb, then there is no way to automatically have it add the columns you need.

您可以使用ModelName。add_to_class(或.contribute_to_class),但是如果您已经运行了syncdb,那么就无法自动地让它添加所需的列。

For maintainable code, you will probably want to extend by sub-classing the desired model in your own app, and use something like south to handle the database migrations, or just use a OneToOneField, and have a related model (like UserProfile is to auth.User).

对于可维护性代码,您可能想要在自己的应用程序中对所需的模型进行子类化,并使用类似于南方的东西来处理数据库迁移,或者只使用OneToOneField,并有一个相关的模型(比如UserProfile是auth.User)。

#2


0  

Take a look to Django model inheritance and abstract classes http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance

查看Django模型继承和抽象类http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table继承