【问题标题】:How to import Session model in __init__.py ? - Django如何在 __init__.py 中导入 Session 模型? - 姜戈
【发布时间】:2021-03-26 06:49:54
【问题描述】:

如何在Django的app/__init__.py中导入Session模型?

我正在尝试更改默认 django 表的名称。 我可以做到这一点,它可以通过更改站点包上的直接链接完美地工作。

但这很糟糕,因为该项目的命名法不同,所以我需要在运行时执行此操作。

我尝试在文件中添加app/__init __.py

from django.contrib.sessions.models import Session
Session._meta.db_table = "my_session"

但我收到此错误:

D:\PyEnv38\lib\site-packages\django\apps\registry.py", line 136, in check_apps_ready
  raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

【问题讨论】:

  • 会话模型是否将abstract 设置为true?
  • 在哪里?它需要在 lib 或 init 中吗?
  • 好像和model属性有关,好久没搞了。
  • 需要做什么?你知道怎么通知吗?

标签: python python-3.x django django-models


【解决方案1】:

如果您想在会话表中提供自定义名称或创建自定义字段,您可以按照以下步骤操作。

定义自定义会话后端:

my_project
    my_project/
        settings.py
        session_backend.py
        ...
    user/
        models.py
        ...
from django.contrib.sessions.backends.db import SessionStore as DBStore
import user


class SessionStore(DBStore):

    @classmethod
    def get_model_class(cls):
        return user.models.MySession

    def create_model_instance(self, data):
        """
        overriding the function to save the changes to db using `session["user_id"] = user.id` .
        This will create the model instance with the custom field values. 
        When you add more field to the custom session model you have to update the function 
        to handle those fields as well.
        """
        obj = super().create_model_instance(data)
        try:
            user_id = data.get('user_id')
        except (ValueError, TypeError):
            user_id = None

        obj.user_id = user_id
        return obj

然后在setting.py 中导入您的自定义类

SESSION_ENGINE = "my_project.session_backend"

在应用程序的models.py 中定义自定义模型,例如user

from django.contrib.sessions.models import Session


class MySession(Session):
    # you can also add custom field if required like this user column which can be the FK to the user table 
    user = models.ForeignKey('user', on_delete=models.CASCADE) 

    class Meta:
        app_label = "user"
        db_table = "my_session"

现在运行以下命令进行迁移

python manage.py makemigrations
python manage.py migrate

完成:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2016-06-14
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多