python - Django 'OneToOneField' 对象没有属性 'id'

标签 python django

我尝试根据默认 User 对象的 id 创建编码的 id 字段,但收到以下错误(完整跟踪):

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()
  File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/default_user/Documents/pumac3/venv/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/default_user/Documents/pumac3/pumac3/registration/models.py", line 52, in <module>
    class Coach(models.Model):
  File "/Users/default_user/Documents/pumac3/pumac3/registration/models.py", line 61, in Coach
    user_id = models.CharField(max_length=254, default=urlsafe_base64_encode(force_bytes(user.id)))
AttributeError: 'OneToOneField' object has no attribute 'id'

我的 models.py 中的 Coach 模型如下所示:

class Coach(models.Model):
    user = models.OneToOneField(User, unique=True)

    # Sets default user values
    user.is_active = False

    # For account activation and password resetting
    user_timestamp = models.IntegerField(default=int(time.time()))
    user_id = models.CharField(max_length=254, default=urlsafe_base64_encode(force_bytes(user.id)))
    user_token = models.CharField(max_length=254, default=default_token_generator.make_token(user))

    name = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=20)

    class Meta:
        verbose_name_plural = "Coaches"
        ordering = ['name']

    def __unicode__(self):
        """Returns the name of the coach if has name, otherwise returns email."""
        if self.name:
            return self.name
        else:
            return self.user.email

    def update_token(self):
        """Updates the user_token and timestamp for password reset or invalid activation"""
        self.user_timestamp = int(time.time())
        self.user_token = default_token_generator.make_token(user)
        self.save()

    @staticmethod
    def is_coach(user):
        return hasattr(user, 'coach')

    @staticmethod
    def authorized(user):
        """Returns a queryset of Coach objects the user can view and modify."""
        if hasattr(user, 'coach'):
            # check that the user is a coach
            return user.coach

    @staticmethod
    def authorized_organizations(user):
        """
        Returns a queryset of organizations the user can view and modify.
        """
        if hasattr(user, 'coach'):
            return user.coach.organizations.all()

我尝试过查看与我的类似的其他问题,但是该人指定了主键,因此 Django 没有创建默认的 id 字段。但是,我没有在 Coach 模型中执行此操作,即使是这样,Django 默认 User 模型不应该包含 id 属性吗?

我怀疑问题在于 id 字段仅在实际创建 User 实例之后才存在,因此我无法为 user_id< 创建值。在创建 User 类的实例后,我是否应该在 models.py 之外实例化该值?

最佳答案

您不能在类的顶层代码中使用实例数据。 在代码运行时(导入时),还没有实例。 如果要使用计算数据初始化实例,请覆盖该类的 __init__ 方法。

关于python - Django 'OneToOneField' 对象没有属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42106898/

相关文章:

python - 将字节数组从 C++ 传递到 Python

python - 如果进程挂起/崩溃,如何重新启动 python 脚本

python - Django pre_delete 信号被忽略

python - 在 Django 的 ManyToManyField 中缓存

python - 在 numpy 中沿一个轴对数据进行分箱

python - 拆分 os.popen 的结果

c# - tensorflow 服务

python - django:按字母顺序对表数据进行排序

python - 从django数据库中检索数据并显示在表中

django - 如何在django创建 View 中保存多对多字段