1

I am really new to Django, I would like to have users, that belong to a company, so many users to a single company. Do I need to copy the existing user model and add to my project? Where would I find the User model to extend?

Sorry if this is not very descriptive it is my first project with python and django.

Charles Bryant
  • 995
  • 2
  • 18
  • 30
  • yes, make a custom user model with a company field https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#specifying-a-custom-user-model – Anentropic Nov 22 '15 at 16:54
  • Possible duplicate of [Extending the User model with custom fields in Django](http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django) – mehmet Nov 22 '15 at 18:11

1 Answers1

3

(If you need many companies to one user) you don't need to copy the user model. Just create a "Company" model and use "ForeignKey". Example:

from django.contrib.auth import get_user_model
User = get_user_model()
class Company(models.Model):
    user = models.ForeignKey(User)

Opposite(If you need many users to one company):

#settings.py
AUTH_USER_MODEL = 'myapp.User'

#myapp.models.py
from django.contrib.auth.models import User as BaseUser, UserManager
class User(BaseUser):
    company = models.ForeignKey(Company)
    # Use UserManager to get the create_user method, etc.
    objects = UserManager()
Aram
  • 221
  • 1
  • 4
  • Does this not relate a Company to a User rather than a User to a Company? – Charles Bryant Nov 22 '15 at 20:55
  • Please read this article: https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one/ – Aram Nov 22 '15 at 21:06
  • 2
    Note that it is in general a good idea to start a Django project with a custom User model, even if you don't change anything (because changing a customer user model later is much easier than changing the default user model later). Doubly so if you have an actual reason. – RemcoGerlich Nov 22 '15 at 21:45