django 自定义用户user模型的三种方法

WBOY
Release: 2016-06-10 15:19:03
Original
1256 people have browsed it

django version: 1.7.1

最简单的推荐:
使用abstractuser扩充fields

复制代码 代码如下:

profiles/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _

# Create your models here.
class KarmaUser(AbstractUser):
karma = models.PositiveIntegerField(_("karma"),default=0,blank=True)
settings.py

AUTH_USER_MODEL = 'profiles.KarmaUser'

2.使用abstractbaseuser

只有当你对user
model里面的默认字段不满的时候才要使用,这个方法只保留了passwork,last_login,is_active三个字段
参考官方文档:
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/

3.使用一对一关系将相关的模型一个个联系起来

这很像django 1.5之前的方式.很适用于创建第三方扩充包的场景,松耦合,不会破坏之前项目的结构.

需要此方法的场景:
- 在自己的django prj下,希望有多重user拥有各自很不相同的字段.或许希望有些用户组合起来一些用户的类型字段,并且希望能在模型层面上解决这些问题.
例子如下:

profiles/models.py

复制代码 代码如下:

from django.conf import settings
from django.db import models

from flavors.models import Flavor

class EaterProfile(models.Model):
# 默认用户资料
user = models.OneToOneField(settings.AUTH_USER_MODEL)
favorite_ice_cream = models.ForeignKey(Flavor,null=True,blank=True)

class ScooperProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
scoops_scooped = models.IntegerField(default=0)

class InventorProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
flavors_invented = models.ManyToManyField(Flavor,null=True,blank=True)

个人认为在我的建站场景中,第二种最合适.正在测试是否可以用抽象类简化模型.待续...

以上3种方法各有优劣,大家根据自己的需求,自由选择吧。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template