Search code examples
pythonsqldjangodjango-authentication

Understanding how the Django Auth app creates its tables


In the models.py file of the Django auth app, there are models for user and group which create their respective tables in the database:

  • class user -> auth_user
  • class group -> auth_group

There is no class user_groups, and yet something fancy happens behind the scenes to also create a table auth_user_groups which tracks which users are in which groups. (Each row contains a single user_id and group_id).

Can someone help me understand how this happens? I may want to replicate this functionality in my own app, where I associate customer models with a group_id.


Solution

  • User and Groups share a ManyToMany relationship.

    See: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/

    groups

    Many-to-many relationship to Group

    https://docs.djangoproject.com/en/2.1/ref/contrib/auth/#django.contrib.auth.models.User.groups