从Django模型中获取对象时出错

时间:2017-02-02 08:42:09

标签: django postgresql django-models

我想获取所有代码模型对象并计算返回对象的长度。我收到了一个我无法理解的错误。

这是我的模特

class Codes(models.Model):
    username = models.CharField(max_length=100)
    code = models.CharField(max_length=10000)
    language = models.CharField(max_length=100)

    def __str__(self):
        return self.language

我使用以下函数从模型中获取所有对象

def get_all_codes(lang):
    queryset = Codes.objects.filter(language = lang)
    return queryset

调用函数

all_codes_of_lang = get_all_codes(lang)

并尝试使用以下方法计算长度:

if len(all_codes_of_lang) > 0:
    print("abc")

导致此错误:

if len(all_codes_of_lang) > 0:
  File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 240, in __len__
    self._fetch_all()
  File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
    results = compiler.execute_sql()
  File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
ProgrammingError: relation "submissions_codes" does not exist
LINE 1: ...odes"."code", "submissions_codes"."language" FROM "submissio...
                                                             ^

-->

2 个答案:

答案 0 :(得分:0)

此问题不是get_all_codes函数或计算长度,而是模型和数据库之间存在同步问题。

运行python manage.py makemigrationspython manage.py迁移到修复程序。

答案 1 :(得分:0)

模型未迁移,这就是您收到此错误的原因。 运行以下命令

  • <receiver android:name=".AlarmBroadcastReceiver" android:enabled="true" android:exported="false"> <intent-filter> <action android:name="action_alarm_notification"/> </intent-filter> </receiver>
  • python manage.py makemigrations