Я пытаюсь создать кодированное поле идентификатора на основе кода по умолчанию объекта пользователя, но получить следующее сообщение об ошибке (полный след):Джанго «OneToOneField» не имеет атрибут «идентификатор»
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
выглядит следующим образом:
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()
Я пытался смотреть на другие проблемы, похожие на меня, но было то, что лицо, указанное первичный ключ, так что нет поля по умолчанию id
был создан Джанго. Тем не менее, я не делаю этого в своей модели Coach
, и даже если это так, не должна ли модель пользователя Django по умолчанию содержать свойство id
?
Я подозреваю, что проблема заключается в том, что поле id
существует только после того, как экземпляр User
фактически создан, поэтому я не могу создать значение для user_id
. Должен ли я искать вместо этого значение за пределами models.py
, после создания экземпляра класса User
?
«OneToOneField» Django предназначен для моделей, где есть уникальное и взаимно однозначное сопоставление с родительской таблицей. Таким образом, parent_id (в вашем случае 'user_id') является основным ключом по умолчанию в таблице. – R4chi7