1

我有以下模型:

class Work(models.Model):
    title = models.CharField(max_length=30)
    amount = models.PositiveIntegerField()
    percent = models.FloatField(validators=[MaxValueValidator
        (100),MinValueValidator(0)])
    drop = models.PositiveIntegerField(default=0)
    assignments = models.ManyToManyField(Assignment)

但是当我创建一些“工作”时,它的行为很奇怪:

In [6]: homework = Work("homework",12,15)

In [7]: homework.save()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
...
#lots and lots of stuff...I will post the extend at the bottom
...
ValueError: invalid literal for int() with base 10: 'homework'

当第一个参数需要 CharField 时,为什么读取第一个参数应该是 int?

我觉得我说的很有道理。homework.title应该是“作业”,homework.amount应该是 12,homework.percent应该是 15,并且homework.drop应该是默认值:0。

有人可以解释为什么会出现此错误以及如何修复它。提前致谢。

完整的错误结果:

In [6]: homework = Work("homework",12,15)

In [7]: homework.save()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 homework.save()

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.pyc in save(self, force_insert, force_update, using, update_fields)
    544 
    545         self.save_base(using=using, force_insert=force_insert,
--> 546                        force_update=force_update, update_fields=update_fields)
    547     save.alters_data = True
    548 

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.pyc in save_base(self, raw, cls, origin, force_insert, force_update, using, update_fields)
    620                 # no force_insert)
    621                 if ((force_update or update_fields) or (not force_insert and
--> 622                         manager.using(using).filter(pk=pk_val).exists())):
    623                     if force_update or non_pks:
    624                         values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.pyc in filter(self, *args, **kwargs)
    665         set.
    666         """
--> 667         return self._filter_or_exclude(False, *args, **kwargs)
    668 
    669     def exclude(self, *args, **kwargs):

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.pyc in _filter_or_exclude(self, negate, *args, **kwargs)
    683             clone.query.add_q(~Q(*args, **kwargs))
    684         else:
--> 685             clone.query.add_q(Q(*args, **kwargs))
    686         return clone
    687 

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.pyc in add_q(self, q_object, used_aliases, force_having)
   1257                 else:
   1258                     self.add_filter(child, connector, q_object.negated,
-> 1259                             can_reuse=used_aliases, force_having=force_having)
   1260                 if force_having:
   1261                     self.having.end_subtree()

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.pyc in add_filter(self, filter_expr, connector, negate, trim, can_reuse, process_extras, force_having)
   1188         else:
   1189             self.where.add((Constraint(alias, col, field), lookup_type, value),
-> 1190                 connector)
   1191 
   1192         if negate:

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/where.pyc in add(self, data, connector)
     69 
     70         if hasattr(obj, "prepare"):
---> 71             value = obj.prepare(lookup_type, value)
     72 
     73         super(WhereNode, self).add(

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/where.pyc in prepare(self, lookup_type, value)
    337     def prepare(self, lookup_type, value):
    338         if self.field:
--> 339             return self.field.get_prep_lookup(lookup_type, value)
    340         return value
    341 

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/__init__.pyc in get_prep_lookup(self, lookup_type, value)
    320             return value
    321         elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
--> 322             return self.get_prep_value(value)
    323         elif lookup_type in ('range', 'in'):
    324             return [self.get_prep_value(v) for v in value]

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/__init__.pyc in get_prep_value(self, value)
    553         if value is None:
    554             return None
--> 555         return int(value)
    556 
    557     def contribute_to_class(self, cls, name):

ValueError: invalid literal for int() with base 10: 'homework' 
4

4 回答 4

2

在 Work 表中创建新记录时需要使用关键字参数。

homework = Work(title = "homework", amount = 12, drop = 15)
homework.save()

您指定参数的顺序无关紧要。如果指定了函数的关键字,例如

def attributes(self, pk='', title='', amount=''):
    ...    

然后您可以在没有关键字的情况下按顺序指定参数。但是,Django 模型不会这样做,因为它们无法猜测您的字段名称是什么。他们会实现更多这样的

def attributes(self, **kwargs):
    ...

其中 kwargs 将是指定的所有关键字参数的字典。然后,Django 模型将根据您传入的任何关键字参数更新数据库。

http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html

于 2013-11-11T02:03:35.327 回答
0

每个 django 模型都有一个自动主键,它的默认名称是id. 使用 Work("homework",12,15) 初始化 Work 模型时,您将“homework”字符串传递给 id 字段。

from product.models import Work
homework = Work("homework",12,15)
print homework.id

#outputs 'homework'

我在 django 文档中也找不到任何保证Model.__init__args 的顺序与字段定义的顺序相同的词(因为元类,顺序可能不同)。因此,您应该使用名称参数(kwargs)。

于 2013-11-11T02:10:59.393 回答
0

不是第一个参数应该是int。它应该是一个字符域,具有数字的内容。Django 正在尝试将其转换为 int,但由于文本是homework- 这不是一个有效数字,所以它失败了。第一个参数应该是id一个整数或一串数字。

您必须指定关键字:

homework = Work(title = "homework", amount = 12, drop = 15)

为什么?因为默认的第一个参数不是标题或用户定义的任何内容,它是 id。因此,如果您想跳过 id(将由 Django 自动设置),可能还有其他一些生成的参数,您必须指定关键字。

于 2013-11-11T01:48:20.987 回答
0

您可以通过简单地实现这一点

Work.objects.create(title="homework", amount=12, drop=15)
于 2013-11-11T05:33:17.027 回答