在 Django rest framework 中,在使用自定义模型时,我需要给 AUTH_USER_MODEL 啥值?

Posted

技术标签:

【中文标题】在 Django rest framework 中,在使用自定义模型时,我需要给 AUTH_USER_MODEL 啥值?【英文标题】:In Django rest framework , on using custom models, what value I need to give to AUTH_USER_MODEL?在 Django rest framework 中,在使用自定义模型时,我需要给 AUTH_USER_MODEL 什么值? 【发布时间】:2016-07-27 01:04:20 【问题描述】:

在 Django rest 框架中,我在模型文件夹中有不同的模型 -

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'rest_framework',
'myapp',
]


AUTH_USER_MODEL = 'myapp.models.UserModel.User'
我的应用程序 设置 dev.py 型号 UserModels.py OrderModels.py ReportingModels.py

UserModels.py

class User(AbstractBaseUser, GuardianUserMixin ,PermissionsMixin):

id = models.AutoField(_('id'),unique=True,primary_key=True)
email = models.EmailField(_('email address'),unique=True)
last_name = models.CharField(_('last name'), max_length=100, blank=True)
first_name = models.CharField(_('first name'), max_length=100, blank=True)
parent_id = models.IntegerField(_('parent id'), default=0)
organization_id = models.IntegerField(_('organization id'), default=0, null=True)
created_at = models.DateTimeField(_('date joined '), default=timezone.now())
updated_at = models.DateTimeField(_('date modified '), default=timezone.now())
incorrect_login = models.IntegerField(_('incorrect login frequency'), default=0)
soft_delete = models.BooleanField(_('soft delete'), default=False, )
group = models.ForeignKey('auth.Group', null=True)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['last_name, first_name, email,organization_id,group_id ']

class Meta:
    app_label = 'zeocuser'
    db_table = 'zeocuser_zeocuser'
    permissions = (
        (
            ('add_user_admin', 'add user admin'),
        )
    )


objects = UserManager()

现在,在 AUTH_USER_MODEL 的 settings.py 中,如果我给出如下值 - AUTH_USER_MODEL = 'myapp.models.UserModel.User' 它不接受它并给出以下错误 -

File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/contrib/admin/models.py", line 32, in <module>
    class LogEntry(models.Model):
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/db/models/base.py", line 158, in __new__
    new_class.add_to_class(obj_name, obj)
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/db/models/base.py", line 299, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/db/models/fields/related.py", line 706, in contribute_to_class
    super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/db/models/fields/related.py", line 306, in contribute_to_class
    lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/db/models/fields/related.py", line 86, in lazy_related_operation
    return apps.lazy_model_operation(partial(function, **kwargs), *model_keys)
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/db/models/fields/related.py", line 84, in <genexpr>
    model_keys = (make_model_tuple(m) for m in models)
  File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/db/models/utils.py", line 13, in make_model_tuple
    app_label, model_name = model.split(".")
ValueError: too many values to unpack (expected 2)

但是,如果我将我的用户模型直接放在应用程序中的 models.py 文件中(而不将其放在模型文件夹中)并给出

AUTH_USER_MODEL = 'myapp.User'

它工作正常。但在那种情况下,我应该如何组织我的其他模型类。请建议。

【问题讨论】:

【参考方案1】:

Django 期望模型位于 .models 命名空间中。

正如https://docs.djangoproject.com/en/1.9/ref/applications/#how-applications-are-loaded 的第 2 点所述:

您必须在应用程序的 models.py 或 models/init.py 中定义或导入所有模型。否则,此时可能无法完全填充应用程序注册表,这可能会导致 ORM 出现故障。

在您的情况下,您需要在 myapp/models/__init__.py 文件中导入模型:

from .UserModels import User, <other models>
from .OrderModels import <other models>
from .ReportingModels import <other models>

等等

【讨论】:

当然,我在 django 中遇到了另一个问题。要制作具有过滤功能的api,例如 /user?email= ,在 urls.py 中,我有 url(r'^api/v1/users/$', UserViews.UserList.as_view(), name='userlist_view'), url(r'^api/v1/users/(?P.+)/$', UserViews.UserList.as_view(), name='userList_view'), 但是 /user? email= 总是转到对应于 api/v1/users/ 的方法。在视图中,我添加了方法- def get_queryset(self): email = self.kwargs.get(self.lookup_url_kwarg) return User.objects.filter(email=email) 但控制不在那里。 您应该尝试使用 /users/?email=(注意 / 之前的 ?) 不,它不起作用。即使尝试:localhost:8000/api/v1/users/?email=abc.xyz@gmail.com/ 它会获取所有用户方法 更多详情请见:***.com/questions/36569058/…

以上是关于在 Django rest framework 中,在使用自定义模型时,我需要给 AUTH_USER_MODEL 啥值?的主要内容,如果未能解决你的问题,请参考以下文章

django使用rest_framework

Django Rest Framework

Django rest framework 身份和权限验证

Django Rest Framework:非模型服务

django-rest-framework - 在可浏览的 API 中自动生成表单?

在 django-rest-framework 中,是不是可以同时使用 oauth 和 session 身份验证?