继承User模型是否更高效有效?我不明白为什么,但我想阅读您的论点。IMNSHO,模型继承一直很痛苦。
然而,这可能无法回答您的问题,但我对 Will Hardy 在此片段中提出的解决方案非常满意。通过利用信号,它会自动为每个新用户创建一个新的用户配置文件。
该链接不太可能消失,但这是我的代码版本略有不同:
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
class AuthUserProfileModelBase(models.base.ModelBase):
# _prepare is not part of the public API and may change
def _prepare(self):
super(AuthUserProfileModelBase, self)._prepare()
def on_save(sender, instance, created, **kwargs):
if created:
self.objects.create(user=instance)
# Automatically link profile when a new user is created
post_save.connect(on_save, sender=User, weak=False)
# Every profile model must inherit this class
class AuthUserProfileModel(models.Model):
class Meta:
abstract = True
__metaclass__ = AuthUserProfileModelBase
user = models.OneToOneField(User, db_column='auth_user_id',
primary_key=True, parent_link=True)
# The actual profile model
class Profile(AuthUserProfileModel):
class Meta:
app_label = 'some_app_label'
db_table = 'auth_user_profile'
managed = True
language = models.CharField(_('language'), max_length=5, default='en')
当然,任何功劳都归功于 Will Hardy。