Reputation: 23
Django version 1.10, python version 3.4
I type and execute this code in manage.py shell:
from tweet.models import Tweet
tweet = Tweet("Parse JSON like a boss", "Admin")
tweet.save()
and receive message with error:
invalid literal for int() with base 10: 'Parse JSON like a Boss'
models.py:
class Tweet(models.Model):
text = models.TextField()
pub_time = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=100)
class Meta:
ordering = ['-pub_time']
Upvotes: 2
Views: 49
Reputation: 53734
When you are not specifying values for all the fields in a model, you should send in the values that you do have as name value pairs.
Tweet(text="Parse JSON like a boss", author="admin")
in fact, it's a best practice to do this all the time so that changes to the model in the future do not break your code elsewhere. Also it's the recommended way in the manual:
To create a new instance of a model, just instantiate it like any other Python class:
class Model(**kwargs)[source]¶ The keyword arguments are simply the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().
Upvotes: 4
Reputation: 43300
If you're not using kwargs, then django iterates over the args you provide in the same order that the fields are inside the internal fields dictionary (Source Code),
What it appears to be doing is trying to assign your text to the id parameter, which only accepts integers.
So yes, as e4c5 shows, you are much better off using kwargs.
Upvotes: 0