等顺应转换

2024-09-28 18:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是django的新手,对文档中写的东西还是有点困惑。 我将django1.8与python2结合使用。 读到这一段about saving an object in db,我感到困惑:

For example, DateField fields use a Python datetime object to store data. Databases don’t store datetime objects, so the field value must be converted into an ISO-compliant date string for insertion into the database.

在网上我发现了非常不同的方法来做这件事,但实际上我真的不明白如何转换一个符合ISO标准的日期字符串!你知道吗

此外,在我的数据库中,我有DateTimeField,DateField,TimeField。。。如何进行此转换以在数据库中保存新对象?你知道吗

谢谢你!你知道吗

编辑: 型号

class CommunityList (models.Model):

      id_community = models.UUIDField (primary_key=True)
      data_creation = models.DateField 
      subcommunity_flag = models.BooleanField

我正在从一个文件导入数据。 这是完整的回溯

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/Community/CommunityApp/CommunityList

Django Version: 1.8
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'CommunityApp')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/DjangoProjects/Community/CommunityApp/views.py" in import_data
  108.                    CommunityList(datareader)
File "/home/DjangoProjects/Community/CommunityApp/views.py" in CommunityList
  80.             subcommunity_flag=row['subcommunity_flag']
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in __init__
  480.                 raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])

Exception Type: TypeError at /Community/CommunityApp/CommunityList
Exception Value: 'data_creation' is an invalid keyword argument for this function

Tags: djangoinpycommunityanfordatamodels
2条回答

你的问题与字段转换无关。你知道吗

您的模型实际上不包含data_creationsubcommunity_flag字段,因为您没有在模型定义中调用字段类。你知道吗

  data_creation = models.DateField()
  subcommunity_flag = models.BooleanField()

我想你在documentation中浏览了那一页的第一部分。你知道吗

What happens when you save?

When you save an object, Django performs the following steps:

我的。你不需要自己做任何转换。你知道吗

相关问题 更多 >