[Answered ]-Django parameters read in wrong order

2đź‘Ť

âś…

You need to use keyword arguments when you create new records in your Work table.

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

The order in which you specify the arguments will not matter. If keywords for a function was specified something like

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

Then you could specify the arguments in order without the keyword. However, Django models don’t do it this way because they can’t guess what the names of your fields will be. They would implement much more like this

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

Where kwargs will be a dictionary of all keyword arguments specified. Django models will then update the db based on any keyword arguments you pass in there.

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

👤Conor Patrick

0đź‘Ť

It’s not that the first parameter should be an int. It should be a charfield, with the content of a number. Django is trying to convert it to an int, but as the text is homework – which is not a valid number, it fails. The first argument should be id, an integer, or a string of number.

You have to specify the keywords :

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

Why? Because the default first argument is not the title or anything user-defined, it’s the id. So, if you want to skip the id (which will be set automatically by Django), and probably a few other generated arguments, you’ll have to specify the keywords.

👤aIKid

0đź‘Ť

Every django model has a auto-primary-key, and its default name is id. When initializing the Work model with Work(“homework”,12,15), you are passing the “homework” string to the id field.

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

#outputs 'homework'

I also can not find any words in the django doc that guarantee the order of Model.__init__ args is as same as the order of field definitions(because of the metaclass, the orders could be different). Thus you should use name parameters(kwargs).

👤Leonardo.Z

0đź‘Ť

You can achieve this by simply

Work.objects.create(title="homework", amount=12, drop=15)
👤Prashant Gaur

Leave a comment