Django参数读错的顺序

时间:2013-11-11 01:46:05

标签: python django django-models parameters

我有以下型号:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

您必须指定关键字:

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

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

答案 2 :(得分:0)

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

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

#outputs 'homework'

我也找不到django doc中保证Model.__init__ args顺序与字段定义顺序相同的任何单词(由于元类,命令可以不同)。因此,您应该使用名称参数(kwargs)。

答案 3 :(得分:0)

您只需

即可实现此目的
Work.objects.create(title="homework", amount=12, drop=15)