首页 文章

在Django中处理多种类型用户的最佳方法

提问于
浏览
0

在我的项目中,我必须处理不同类型的用户,例如 costumersemployers . 每种类型的用户都有自己的字段和权限:客户可以购买东西,而雇主则不能 .

我已经阅读了Django文档,看起来有两种选择:

  • 使用 AbstractUser 课程并将 all 添加到客户和雇主的字段中 . 然后使用 permission system 授予/撤消权限或为每种类型的用户创建一个组 . 这里的缺点是有未使用的字段 .

  • 采用代理模型:

from django.contrib.auth.models import User
from django.db import models 

 class Costumer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE) 

 class Meta:
    db_table = 'costumers'
    permissions = (
        ("access_this", "User may access this"),
    )
    ordering = []
 

 class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE) 

 class Meta:
    db_table = 'employers'
    permissions = (
        ("access_that", "User may access that"),
    )
    ordering = []

这个案例似乎更合理但我不喜欢使用 @permission_required 而不是检查类型(如果用户有特定字段),因为它似乎更合法的Django系统 .

那么到底,接近这种情况的最佳方法是什么?

1 回答

  • 0

    第一种解决方案要好得多 .

    这里的缺点是有未使用的字段 .

    我不同意这一点,你不必存储 User 模型中的所有字段 . 另外,如果你真的很重要 .


    你可以扩展 AbtractUser 并使用一些组合;你不必把所有的字段放在那里:

    class User(AbstractUser):
         email = ...
         ...
         # for the employer, let's say you want to save the company details
         company = models.ForeignKey('myapp.Company', null=True, blank=True)
         ...
         # for the customer
         customer_details = models.ForeignKey('...')
    

    这样你可以记录一个 user_type 如果你想要或从外键中推断出类型(如果有公司,那就是雇主) .


    为了帮助您更好地使用该模型,我需要了解您的应用程序中雇主与客户的区别 . 请注意,使用该解决方案, User 的实例可能都是 .


    关于权限,我觉得这是一个单独的问题;我建议你最后排序 . 如果您选择的设计接近现实并且您可以使用这些功能;添加自定义权限将非常简单 .

相关问题