使用 Django shell 创建模型条目时出现 Django 错误

Posted

技术标签:

【中文标题】使用 Django shell 创建模型条目时出现 Django 错误【英文标题】:Django Error when creating model entries with Django shell 【发布时间】:2018-04-12 05:29:42 【问题描述】:

我的模型看起来像这样。

class Test(models.Model):
    eval_id = models.ForeignKey(Evaluation, on_delete=models.CASCADE)
    teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    class_id = models.ForeignKey(Class, on_delete=models.CASCADE)
    score1 = models.IntegerField()
    score2 = models.IntegerField()

    class Meta:
        unique_together = ('eval_id','teacher_id','class_id')

这里eval_id、teacher_id和class_id在各自的模型中进行了相应的定义

eval_id = models.IntegerField(primary_key=True)
teacher_id = models.CharField(max_length=10, primary_key=True)
co_id = models.CharField(primary_key = True, max_length=5)

教师示范课:

 class Teacher(models.Model):
        teacher_id = models.CharField(max_length=10, primary_key=True)
        teacher_name = models.CharField(max_length=30)
        teacher_age = models.IntegerField()
        teacher_doj = models.DateField()
        subjects = models.ManyToManyField(Subject)

        def __str__(self):
            return self.teacher_name

当我尝试通过 shell 为模型创建条目时出现以下错误

from trial.models import Test
>>> t1 = Test('1','AC23002','C001','48','50')

我收到以下错误

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 807, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 837, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 904, in _save_table
    forced_update)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 954, in _do_update
    return filtered._update(values) > 0
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/query.py", line 664, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 1199, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 871, in execute_sql
    sql, params = self.as_sql()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 1165, in as_sql
    val = field.get_db_prep_save(val, connection=self.connection)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/related.py", line 963, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", line 770, in get_db_prep_save
    prepared=False)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", line 762, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", line 1853, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'AC23003'

谁能帮我找出对象创建中的错误。

教师表如下:

mysql> select * from trial_teacher;
+------------+--------------+-------------+-------------+
| teacher_id | teacher_name | teacher_age | teacher_doj |
+------------+--------------+-------------+-------------+
| AC23001    | Tina         |          32 | 2017-04-10  |
| AC23002    | Rina         |          31 | 2009-04-10  |
| AC23003    | Tom          |          35 | 2009-04-10  |
| AC23004    | Henry        |          56 | 2009-04-10  |
| AC23005    | Simon        |          32 | 2009-05-10  |
+------------+--------------+-------------+-------------+
12 rows in set (0.00 sec)

mysql> describe trial_teacher;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| teacher_id   | varchar(10) | NO   | PRI | NULL    |       |
| teacher_name | varchar(30) | NO   |     | NULL    |       |
| teacher_age  | int(11)     | NO   |     | NULL    |       |
| teacher_doj  | date        | NO   |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+

评估表:

mysql> mysql> select * from trial_evaluation;
+---------+------------+----------------------------+
| eval_id | eval_name  | date                       |
+---------+------------+----------------------------+
|       1 | 2014_Term1 | 2017-01-01 10:30:00.000000 |
|       2 | 2014_Term2 | 2014-04-01 10:30:00.000000 |
|       3 | 2014_Term3 | 2014-11-01 08:30:00.000000 |
+---------+------------+----------------------------+

类表中同样存在'C001'

【问题讨论】:

teacher_id 应该接收模型教师的主键,但您给出的字符串是 'AC23003'。 但我已将teacher_id 定义为我的教师表中的主键。那我该如何纠正呢? 没什么可纠正的。使用 shell 创建对象时,只需传递 Teacher 表中一条记录的主键即可。 'AC23003'本身就是teacher表中的主键。我已更新我的问题以包含教师表的详细信息。 哦,好吧。你也可以用教师模型更新问题吗? 【参考方案1】:

试试这个。

Test(eval_id_id='1',teacher_id_id='AC23002',class_id_id='C001',score1='48',score2='50')

Django 为所有与键相关的名称附加“_id”。因此,如果您直接使用键值,请使用“_id”。

或,

使用模型中描述的字段名称时。

Test(eval_id = Evaluation.objects.get(eval_id=xxx),...)

第一种方法很有效。

【讨论】:

谢谢。当我使用您建议的参数传递值时,它工作正常!

以上是关于使用 Django shell 创建模型条目时出现 Django 错误的主要内容,如果未能解决你的问题,请参考以下文章

api rest 调用更新 django 模型时出现错误 415

制作 django AJAX likes 时出现操作错误

在 Django 1.8 或更高版本中填充时出现“模型尚未加载”错误

查询数据库时出现 Django 编码错误

在我更改了一些模型字段(Django)之后,尝试访问 django admin 时出现 /admin/myapp/mymodel 的 TypeError

Django Admin - 创建“临时”条目