Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override models defined in installed apps in Django?

Tags:

django

Is it possible to redefine a model used in an INSTALLED_APP without modifying the app in question? For example, django-basic-blog has a Post model which I would like to add a field to. I could edit django-basic-blog directly but for code portability I'd like to build on top of it. I don't want to subclass as I want to preserve all existing references to the Post model. Thanks in advance!

like image 334
Hakan B. Avatar asked Nov 24 '10 22:11

Hakan B.


People also ask

Which file is responsible for the configurations of the Django applications?

Insights about settings.py file. A Django settings file contains all the configuration of your Django Project.

What file contains the list of Installed_apps in a Django project?

In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer's comfort.


1 Answers

  1. If you subclass the original fields will be still stored in the original table, so references would stay valid.

  2. If you want to monkey-patch an existing class, which is mostly not the recommendable dirty method, you could use contribute_to_class in some models.py file that will be loaded in an app after the one you want to modify:

models.py:

from django.db.models import CharField
from blog.models import Post
CharField(max_length="100").contribute_to_class(Post, 'new_field')

If you do it like this, you always have to bare the risk that your changes can clash with other pieces of code and that your code will be harder to maintain!

like image 141
Bernhard Vallant Avatar answered Sep 28 '22 22:09

Bernhard Vallant