2016-08-04 54 views
2

Django的1.10版,Python版本3.4無法創建條目

I型和執行該代碼manage.py殼:

from tweet.models import Tweet 
tweet = Tweet("Parse JSON like a boss", "Admin") 
tweet.save() 

,並收到錯誤消息:

invalid literal for int() with base 10: 'Parse JSON like a Boss'

模型.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'] 

回答

4

如果您沒有爲模型中的所有字段指定值,則應該發送您具有名稱值對的值。

Tweet(text="Parse JSON like a boss", author="admin") 

其實,這是做這一切的時候,這樣的變化在未來的模型中不別處破壞你的代碼的最佳做法。此外它在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().

+0

有趣的事實:當我嘗試輸入 tweet = Tweet(0,「Test」,「admin」) 沒關係。也許問題在編號 – MaxTester

+0

是的,這是令人不愉快的django可能是挑選id域的測試,但推薦的方式來創建新的實例與kwargs。請參閱更新 – e4c5

0

如果你不使用kwargs,那麼Django的迭代你以相同的順序提供ARGS的字段是內部字段字典(Source Code),

它似乎在做的是試圖將你的文本分配給id參數,它只接受整數。

所以是的,正如e4c5所示,使用kwargs會更好。