1

I have an app in my venv and I wish to extend the model but I don't really want to go into the venv and start editing the files.

Is it possible to extend the model and addd fields to it without editing the models file itself. I tried importing it somewhere else and adding variables, but that didn't work, at least initially.

bakkal
  • 54,350
  • 12
  • 131
  • 107
Joff
  • 11,247
  • 16
  • 60
  • 103

1 Answers1

1

Simply monkey patching the model to add a field isn't sufficient, because you'd still need that app to create a DB migration for that field to appear in the actual database. (It doesn't seem like you're trying to add a field or a behavior purely on a Python level, because for that monkey patching, or a @property or a proxy model would have worked fine)

Let's say you do come up with a "hack/script/solution" to migrate the DB, you will be using that app in a version that is different from the official one, so in the future when you'll want to upgrade the app's version, you can run into issues.

Fork your own version and use it as a dependency

So if you don't mind diverging* from the upstream official app, I would fork the app. Meaning I clone their repository, add my field into the model in their models.py, generate the DB migrations, commit all those back into the repository. Then instead of installing the official app, I install my version into the virtual environment. (pip can install from Git e.g., your app doesn't need to be on PyPI)

*Who knows maybe the app's maintainers will accept a pull request from you and put your changes in the official repo

Subclass the model

If it works for you, you can also subclass the original model, add the field you want. So your app can use the extended class you created, and the original app can use the fields/methods that already existed in its original model.

bakkal
  • 54,350
  • 12
  • 131
  • 107
  • hmm, thanks for the info. I think the app will have some good developments in the future so I would like to stay with it and not mess with it too much if possible. I had an idea... the app is related to the auth_user_model by OneToOneField. Can I change the auth_user_model before the app ties itself to it? Or can I add a different "section" of profile into one of my app models and also relate it to the auth_user_model? – Joff Feb 01 '16 at 01:54
  • @deltaskelta Which model exactly do you want to change and for what purpose? Because if you can use your own `UserProfile` model that is a one-to-one with `User`, then you can simply extend `UserProfile`. Otherwise see this answer if it works for your case: http://stackoverflow.com/questions/35198113/how-to-modify-a-django-model/35198325#35198325 – bakkal Feb 10 '16 at 11:26