Django模型继承异常还是预期的行为?

时间:2019-01-16 01:57:09

标签: python django python-3.x

我目前正在使用django 1.11进行项目,并且费了一些时间来寻找错误原因。我不知道这是错误还是预期的行为,并希望有人可以阐明问题或向正确的方向指出。我已经搜索了类似的问题,但没有发现任何相似的东西。

问题如下,我有一个基本模型类:

class BaseModel(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(default=timezone.now, editable=False)
    modified_at = models.DateTimeField(default=timezone.now, editable=False)

    def save(self, *args, **kwargs):
       if self.pk:
           self.modified_at = timezone.now
       return super(BaseModel, self).save(*args, **kwargs)

并且在每个模型上都可以正常工作,直到我需要覆盖另一个模型上的默认保存行为:

class Agent(BaseModel):
    TIME_ZONES = [(tz, tz) for tz in pytz.common_timezones]

    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='agent',
    )

    time_zone = models.CharField(choices=TIME_ZONES,
                                 default=settings.TIME_ZONE,
                                 max_length=100)

    phone = models.CharField(max_length=50, null=True, blank=True)
    email = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
        return self.user.username

    def save(self, *args, **kwargs):
        self.email = self.user.email
        return super(Agent, self).save(*args, **kwargs)

当我尝试将Agent模型的新实例保存到执行Agent(user=user).save()的数据库时,引发了一个异常,说expected string or bytes-like object

如果执行以下操作之一,则不会引发异常:

  • 更改Agent模型以直接从models.Model继承并声明'created_at and modified_at in the Agent`类
  • Agent类的save方法上的超级调用更改为super(BaseModel, self).super(*args, **kwargs),并且仍然继承自BaseModel

正如我之前所说,我不知道我是否缺少某些东西,这是预期的行为,还是一个错误。预先感谢您的帮助。

完整的回溯是这样的:

Traceback:  

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41.             response = get_response(request)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187.                 response = self.process_exception_by_middleware(e, request)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
58.         return view_func(*args, **kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/views/generic/base.py" in view
68.             return self.dispatch(request, *args, **kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
67.             return bound_func(*args, **kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
76.             return view(request, *args, **kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/var/task/backend/users/views/sign_up.py" in dispatch
19.         return super(SignUpViewSet, self).dispatch(*args, **kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
483.             response = self.handle_exception(exc)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
443.             self.raise_uncaught_exception(exc)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
480.             response = handler(request, *args, **kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/generics.py" in post
192.         return self.create(request, *args, **kwargs)

File "/var/task/backend/users/views/sign_up.py" in create
31.         user = self.perform_create(serializer)

File "/var/task/backend/users/views/sign_up.py" in perform_create
41.         user = serializer.save(self.request)

File "/var/task/backend/users/serializers/sign_up.py" in save
40.         agent.save()

File "/var/task/backend/users/models/agent.py" in save
31.         return super(Agent, self).save(*args, **kwargs)

File "/var/task/backend/core/models.py" in save
69.         return super(BaseModel, self).save(*args, **kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/base.py" in save
806.                        force_update=force_update, update_fields=update_fields)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/base.py" in save_base
836.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/base.py" in _save_table
903.                                       forced_update)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/base.py" in _do_update
953.         return filtered._update(values) > 0

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/query.py" in _update
661.         return query.get_compiler(self.db).execute_sql(CURSOR)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1191.         cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
863.             sql, params = self.as_sql()

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql
1157.                 val = field.get_db_prep_save(val, connection=self.connection)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
766.                                       prepared=False)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
1455.             value = self.get_prep_value(value)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in get_prep_value
1434.         value = super(DateTimeField, self).get_prep_value(value)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in get_prep_value
1292.         return self.to_python(value)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in to_python
1395.             parsed = parse_datetime(value)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/utils/dateparse.py" in parse_datetime
94.     match = datetime_re.match(value)

Exception Type: TypeError at /api/v1/auth/sign-up/
Exception Value: expected string or bytes-like object

1 个答案:

答案 0 :(得分:3)

self.modified_at = timezone.now

这是您的问题。您打算做timezone.now()。从函数引用而不是字符串或datetime对象解析日期时会崩溃。如果绕过BaseModel类的save方法,则不会触发该行为。