0

In my Django app, I need to create a User Model with some extra fields. For DB performance, I would like to avoid to make a join everytime I want to access those fields. At DB level I would like to produce an ALTER TABLE on the user table to add those fields, or even a CREATE TABLE with all the fields I need on the app initialization would be fine, since I'm still in development.

I've found two solutions to extend the User Model (reported below) but both are inconsistent with my choice of avoiding JOINs.

models.py (Solution 1)
from django.db import models

class Person(models.Model):
    # Aggregate using a OneToOneField on User
    user = models.OneToOneField(User)
    age = models.PositiveSmallIntegerField()

models.py (Solution 2)
from django.contrib.auth.models import User

class Person(User):
     # Inheriting from User
     age = models.PositiveSmallIntegerField() 

SQL (Solution 1)
/* Aggregate using a OneToOneField on User */
BEGIN;
CREATE TABLE "people_person" (
 "id" integer NOT NULL PRIMARY KEY,
 "user_id" integer NOT NULL UNIQUE REFERENCES "auth_user" ("id"),
 "age" smallint unsigned NOT NULL
);
 COMMIT;

SQL (Solution 2)
/* Inheriting from User */
BEGIN;
CREATE TABLE "people_person" (
 "user_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "auth_user" ("id"),
 "age" smallint unsigned NOT NULL
);
 COMMIT;
second
  • 28,029
  • 7
  • 75
  • 76

1 Answers1

1

From django 1.5, it is possible to replace the user model rather than extending it.

https://docs.djangoproject.com/en/dev/releases/1.5/#configurable-user-model

In django 1.4 or older, there the "profile" attribute on the user gets some special caching, which may or may not be good enough for your requirements.

Rasmus Kaj
  • 4,224
  • 1
  • 20
  • 23