django.core.exceptions.FieldError:无法解析关键字' timestamp'进入田野

时间:2017-03-23 18:09:48

标签: python django python-3.x

欢迎朋友们,

不幸的是我有FieldError。请帮忙

环境:

Django Version: 1.10.6
Python Version: 3.5.2

utils.py

import datetime
from django.utils import timezone
from django.contrib.contenttypes.models import ContentType
from .models import Action

def create_action(user, verb, target=None):
    now = timezone.now()
    last_minute = now - datetime.timedelta(seconds=60)
    similar_actions = Action.objects.filter(user_id=user.id, verb=verb, timestamp__gte=last_minute)
    if target:
        target_ct = ContentType.objects.get_for_model(target)
        similar_actions = similar_actions.filter(
                                         target_ct=target_ct,
                                         target_id=target.id)
    if not similar_actions:
        # Nie znaleziono żadnych akcji.
        action = Action(user=user, verb=verb, target=target)
        action.save()
        return True
    return False

models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

class Action(models.Model):
   user = models.ForeignKey(User,
                         related_name='actions',
                         db_index=True)
   verb = models.CharField(max_length=255)

   target_ct = models.ForeignKey(ContentType,
                              blank=True,
                              null=True,
                              related_name='target_obj')
   target_id = models.PositiveIntegerField(null=True,
                                        blank=True,
                                        db_index=True)
   target = GenericForeignKey('target_ct', 'target_id')
   created = models.DateTimeField(auto_now_add=True,
                               db_index=True)

   class Meta:
       ordering = ('-created',)

我从Django Shell收到了这个错误回溯:

 django.core.exceptions.FieldError: Cannot resolve keyword 'timestamp' 
 into field. Choices are: created, id, target, target_ct, 
 target_ct_id, target_id, user, user_id, verb
[23/Mar/2017 17:20:46] "POST /account/users/follow/ HTTP/1.1" 500 18933

我从浏览器控制台收到此错误:

POST http://127.0.0.1:8000/account/users/follow/ 500 (Internal Server Error)

有人应对此事吗?

有人对此有任何建议吗?

2 个答案:

答案 0 :(得分:3)

从错误中它应该是这样的:

similar_actions = Action.objects.filter(created__gte=last_minute, user_id=user.id, verb=verb)

您正在查询不存在的timestamp模型的Action属性。可用的选择是:

created, id, target, target_ct, target_ct_id, target_id, user, user_id, verb

因此,您应该根据Action模型的属性(或其中任何关系)来查询数据库。

答案 1 :(得分:0)

当我删除第二个数据库中的一列时,我遇到了相同的错误。

您可以尝试重置迁移:

  1. 删除项目中的所有迁移文件。 浏览每个项目应用程序迁移文件夹( your_app / migrations / ),并删除其中的所有内容,但 init .py文件除外。
  2. 运行makemigrationsmigrate

不确定您的情况,但这在我的情况下解决了相同的错误。