开发者社区> 问答> 正文

Django模型继承奇怪或预期的行为?

一码平川MACHEL 2019-01-16 17:31:34 439

我目前正在使用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模型实例保存到db中时Agent(user=user).save(),引发了异常expected string or bytes-like object。

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

将Agent模型更改为直接继承models.Model并声明'created_at andmodified_at in theAgent`类
将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

  1. response = get_response(request)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response

  1. 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

  1. 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

  1. return view_func(args, *kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/views/generic/base.py" in view

  1. return self.dispatch(request, args, *kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper

  1. return bound_func(args, *kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper

  1. return view(request, args, *kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func

  1. return func.__get__(self, type(self))(args2, *kwargs2)

File "/var/task/backend/users/views/sign_up.py" in dispatch

  1. return super(SignUpViewSet, self).dispatch(args, *kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/views.py" in dispatch

  1. response = self.handle_exception(exc)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception

  1. self.raise_uncaught_exception(exc)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/views.py" in dispatch

  1. response = handler(request, args, *kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/rest_framework/generics.py" in post

  1. return self.create(request, args, *kwargs)

File "/var/task/backend/users/views/sign_up.py" in create

  1. user = self.perform_create(serializer)

File "/var/task/backend/users/views/sign_up.py" in perform_create

  1. user = serializer.save(self.request)

File "/var/task/backend/users/serializers/sign_up.py" in save

  1. agent.save()

File "/var/task/backend/users/models/agent.py" in save

  1. return super(Agent, self).save(args, *kwargs)

File "/var/task/backend/core/models.py" in save

  1. return super(BaseModel, self).save(args, *kwargs)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/base.py" in save

  1. 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

  1. 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

  1. forced_update)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/base.py" in _do_update

  1. return filtered._update(values) > 0

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/query.py" in _update

  1. 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

  1. 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

  1. sql, params = self.as_sql()

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql

  1. 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

  1. prepared=False)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value

  1. 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

  1. 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

  1. return self.to_python(value)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in to_python

  1. parsed = parse_datetime(value)

File "/root/.virtualenvs/ve/lib/python3.6/site-packages/django/utils/dateparse.py" in parse_datetime

  1. match = datetime_re.match(value)

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

SQL API Python
分享到
取消 提交回答
全部回答(1)
  • 一码平川MACHEL
    2019-07-17 23:25:42

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

    0 0

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题