飞翔的彼得猪 发表于 2020-7-24 21:39:58

python 文件迁移出现TypeError: Field 'id' expected a number but got datetime.d...

TypeError: Field 'id' expected a number but got datetime.datetime(2020, 7, 24, 13, 35, 0, 162476, tzinfo=<UTC>).应该怎么解决

txxcat 发表于 2020-7-24 22:45:32

类型错误:字段'id'需要数字但是获得datetime对象。
这个具体什么问题要看代码才清楚。

飞翔的彼得猪 发表于 2020-7-24 23:05:23

txxcat 发表于 2020-7-24 22:45
类型错误:字段'id'需要数字但是获得datetime对象。
这个具体什么问题要看代码才清楚。

model.py


from django.db import models
from django.contrib.auth.models import User

class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)



    def __str__(self):
      return self.text

class Entry(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
      verbose_name_plural = 'entries'

    def __str__(self):
      return self.text[:50] + '...'

飞翔的彼得猪 发表于 2020-7-24 23:06:07

txxcat 发表于 2020-7-24 22:45
类型错误:字段'id'需要数字但是获得datetime对象。
这个具体什么问题要看代码才清楚。

应该是这个吧

txxcat 发表于 2020-7-24 23:55:27

飞翔的彼得猪 发表于 2020-7-24 23:06
应该是这个吧

这段代码不会导致这个报错,你最好把完整报错信息发出来看看。

飞翔的彼得猪 发表于 2020-7-25 00:13:55

txxcat 发表于 2020-7-24 23:55
这段代码不会导致这个报错,你最好把完整报错信息发出来看看。

models.py

from django.db import models
from django.contrib.auth.models import User

class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True,editable=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)




    def __str__(self):
      return self.text

class Entry(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
      verbose_name_plural = 'entries'

    def __str__(self):
      return self.text[:50] + '...'


Views.py

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse


from .models import Topic,Entry
from .forms import TopicForm, EntryForm


def index(request):
    return render(request, 'learning_logs/index.html')

@login_required
def topics(request):
    topics = Topic.objects.filter(owner=request.user).order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

@login_required
def topic(request, topic_id):
    topic = Topic.objects.get(id=topic_id)
    if topic.owner != request.user:
      raise Http404
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic,'entries': entries}
    return render(request,'learning_logs/topic.html', context)


@login_required
def new_topic(request):
    if request.method !='POST':
      form = TopicForm()

    else:
      form = TopicForm(request.POST)
      if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))

    context= {'form':form}
    return render(request, 'learning_logs/new_topic.html', context)

@login_required
def new_entry(request,topic_id):
    topic = Topic.objects.get(id=topic_id)
    if topic.owner != request.user:
      raise Http404

    if request.method != 'POST':
      form = EntryForm()

    else:
      form = EntryForm(data=request.POST)
      if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',
                                                args=))

    context = {'topic': topic, 'form': form}
    return render(request, 'learning_logs/new_entry.html', context)

@login_required
def edit_entry(request,entry_id):
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    if topic.owner != request.user:
      raise Http404

    if request.method != 'POST':
      form = EntryForm(instance=entry)

    else:
      form = EntryForm(instance=entry,data=request.POST)
      if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',
                                                args=))
    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'learning_logs/edit_entry.html', context)

飞翔的彼得猪 发表于 2020-7-25 00:16:06

txxcat 发表于 2020-7-24 23:55
这段代码不会导致这个报错,你最好把完整报错信息发出来看看。

主要是我将数据关联到用户时,修改了model.py创建了owner,然后迁移就报错了,不知道是不是因为owner

飞翔的彼得猪 发表于 2020-7-25 00:19:57

txxcat 发表于 2020-7-24 23:55
这段代码不会导致这个报错,你最好把完整报错信息发出来看看。


虚拟迁移报错
(ll_env) F:\learning_log>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, learning_logs, sessions
Running migrations:
Applying learning_logs.0004_topic_owner...Traceback (most recent call last):
File "F:\learning_log\ll_env\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get
_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "manage.py", line 21, in <module>
    main()
File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
File "F:\learning_log\ll_env\lib\site-packages\django\core\management\__init__.py", line 401, in execu
te_from_command_line
    utility.execute()
File "F:\learning_log\ll_env\lib\site-packages\django\core\management\__init__.py", line 395, in execu
te
    self.fetch_command(subcommand).run_from_argv(self.argv)
File "F:\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 328, in run_from_
argv
    self.execute(*args, **cmd_options)
File "F:\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 369, in execute
    output = self.handle(*args, **options)
File "F:\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
File "F:\learning_log\ll_env\lib\site-packages\django\core\management\commands\migrate.py", line 231,
in handle
    post_migrate_state = executor.migrate(
File "F:\learning_log\ll_env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate

    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "F:\learning_log\ll_env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrat
e_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "F:\learning_log\ll_env\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_m
igration
    state = migration.apply(state, schema_editor)
File "F:\learning_log\ll_env\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "F:\learning_log\ll_env\lib\site-packages\django\db\migrations\operations\fields.py", line 110, i
n database_forwards
    schema_editor.add_field(
File "F:\learning_log\ll_env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add
_field
    self._remake_table(model, create_field=field)
File "F:\learning_log\ll_env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _re
make_table
    self.effective_default(create_field)
File "F:\learning_log\ll_env\lib\site-packages\django\db\backends\base\schema.py", line 303, in effect
ive_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
File "F:\learning_log\ll_env\lib\site-packages\django\db\models\fields\related.py", line 939, in get_d
b_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
File "F:\learning_log\ll_env\lib\site-packages\django\db\models\fields\__init__.py", line 821, in get_
db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
File "F:\learning_log\ll_env\lib\site-packages\django\db\models\fields\__init__.py", line 2365, in get
_db_prep_value
    value = self.get_prep_value(value)
File "F:\learning_log\ll_env\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get
_prep_value
    raise e.__class__(
TypeError: Field 'id' expected a number but got datetime.datetime(2020, 7, 24, 16, 18, 30, 203285, tzinf
o=<UTC>).

打开网页 报错

http://127.0.0.1:8000/learning_logs/topic/

飞翔的彼得猪 发表于 2020-7-25 00:20:44

http://127.0.0.1:8000/learning_logs/topic/

txxcat 发表于 2020-7-25 22:27:21

后面的图片打不开,现在只能判断是该由DateTimeField处理的数据被IntegerField处理了导致的错误,至于为什么会出现这个问题,是bug还是数据错误无从得知,你需要自己对整个环境进行更多的分析测试才有机会找出问题。
页: [1]
查看完整版本: python 文件迁移出现TypeError: Field 'id' expected a number but got datetime.d...