[Fixed]-How to use a model in a Python Django project for multiple applications?

1👍

If the linked model is in another app, you need to refer to that in the destination string.

exch_usr = models.ForeignKey('auth.User', on_delete=models.PROTECT)

Note, you do not need to import User at all.

0👍

If you are already importing User model on that models.py, you can just set it to ForeignKey. be aware that it’s not a string.

exch_usr = models.ForeignKey(User, on_delete=models.PROTECT)
👤tell k

0👍

The @danielr ‘s answer is perfect but I have a recommendation for you @Parry. So if the User model might be swapped out for another(thinking in the future) and to make your application as reusable as possible you should use the settings.AUTH_USER_MODEL as a references in your models . More information on customizing and referencing the User model can be found at https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#referencing-the-user-model. And inside your code you must use the get_user_model Django(to create User references ) utility to create this switch in a clean way.

class SomeClass(models.Model):
....
custome_user = models.ForeignKey(settings.AUTH_USER_MODEL)

and to make references to User properties:

from django.contrib.auth import get_user_model
User = get_user_model()
class AnotherClass(models.Model):
....
username = User.USERNAME_FIELD

👤Reidel

Leave a comment