新手求助养渴,windows版本的python沒有termios這個模塊是沒有。如果想在windows下跑键兜,得裝cygwin
E:\ScienceSoft\Python\Django\learn_models> python manage.py syncdb
Unknown command: 'syncdb'
Type 'manage.py help' for usage.
E:\ScienceSoft\Python\Django\learn_models>manage.py help
Type 'manage.py help <subcommand>' for help on a specific subcommand.
Available subcommands:
[auth]
changepassword
createsuperuser
[contenttypes]
remove_stale_contenttypes
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
[sessions]
clearsessions
[staticfiles]
collectstatic
findstatic
runserver
E:\ScienceSoft\Python\Django\learn_models>
E:\ScienceSoft\Python\Django\learn_models>python manage.py syncdb
Unknown command: 'syncdb'
Type 'manage.py help' for usage.
E:\ScienceSoft\Python\Django\learn_models>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, people, sessions
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won
't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage
.py migrate' to apply them.
E:\ScienceSoft\Python\Django\learn_models>python manage.py shell
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AM
D64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from people.models import BlogPost
In [2]: BlogPost.objects.create(title="sky", body="tiankongzhicheng")
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\ut
ils.py in execute(self, sql, params)
64 else:
---> 65 return self.cursor.execute(sql, params)
66
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\sq
lite3\base.py in execute(self, query, params)
327 query = self.convert_query(query)
--> 328 return Database.Cursor.execute(self, query, params)
329
OperationalError: no such table: people_blogpost
The above exception was the direct cause of the following exception:
OperationalError Traceback (most recent call last)
<ipython-input-2-5ba60fd7532b> in <module>()
----> 1 BlogPost.objects.create(title="sky", body="tiankongzhicheng")
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\mana
ger.py in manager_method(self, *args, **kwargs)
83 def create_method(name, method):
84 def manager_method(self, *args, **kwargs):
---> 85 return getattr(self.get_queryset(), name)(*args, **kwarg
s)
86 manager_method.__name__ = method.__name__
87 manager_method.__doc__ = method.__doc__
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\quer
y.py in create(self, **kwargs)
392 obj = self.model(**kwargs)
393 self._for_write = True
--> 394 obj.save(force_insert=True, using=self.db)
395 return obj
396
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base
.py in save(self, force_insert, force_update, using, update_fields)
805
806 self.save_base(using=using, force_insert=force_insert,
--> 807 force_update=force_update, update_fields=update_f
ields)
808 save.alters_data = True
809
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base
.py in save_base(self, raw, force_insert, force_update, using, update_fields)
835 if not raw:
836 self._save_parents(cls, using, update_fields)
--> 837 updated = self._save_table(raw, cls, force_insert, force_upd
ate, using, update_fields)
838 # Store the database on which the object was saved
839 self._state.db = using
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base
.py in _save_table(self, raw, cls, force_insert, force_update, using, update_fie
lds)
921
922 update_pk = meta.auto_field and not pk_set
--> 923 result = self._do_insert(cls._base_manager, using, fields, u
pdate_pk, raw)
924 if update_pk:
925 setattr(self, meta.pk.attname, result)
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\base
.py in _do_insert(self, manager, using, fields, update_pk, raw)
960 """
961 return manager._insert([self], fields=fields, return_id=update_p
k,
--> 962 using=using, raw=raw)
963
964 def delete(self, using=None, keep_parents=False):
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\mana
ger.py in manager_method(self, *args, **kwargs)
83 def create_method(name, method):
84 def manager_method(self, *args, **kwargs):
---> 85 return getattr(self.get_queryset(), name)(*args, **kwarg
s)
86 manager_method.__name__ = method.__name__
87 manager_method.__doc__ = method.__doc__
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\quer
y.py in _insert(self, objs, fields, return_id, raw, using)
1074 query = sql.InsertQuery(self.model)
1075 query.insert_values(fields, objs, raw=raw)
-> 1076 return query.get_compiler(using=using).execute_sql(return_id)
1077 _insert.alters_data = True
1078 _insert.queryset_only = False
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\sql\
compiler.py in execute_sql(self, return_id)
1097 with self.connection.cursor() as cursor:
1098 for sql, params in self.as_sql():
-> 1099 cursor.execute(sql, params)
1100 if not (return_id and cursor):
1101 return
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\ut
ils.py in execute(self, sql, params)
78 start = time()
79 try:
---> 80 return super(CursorDebugWrapper, self).execute(sql, params)
81 finally:
82 stop = time()
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\ut
ils.py in execute(self, sql, params)
63 return self.cursor.execute(sql)
64 else:
---> 65 return self.cursor.execute(sql, params)
66
67 def executemany(self, sql, param_list):
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\utils.py in
__exit__(self, exc_type, exc_value, traceback)
92 if dj_exc_type not in (DataError, IntegrityError):
93 self.wrapper.errors_occurred = True
---> 94 six.reraise(dj_exc_type, dj_exc_value, traceback)
95
96 def __call__(self, func):
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\six.py i
n reraise(tp, value, tb)
683 value = tp()
684 if value.__traceback__ is not tb:
--> 685 raise value.with_traceback(tb)
686 raise value
687
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\ut
ils.py in execute(self, sql, params)
63 return self.cursor.execute(sql)
64 else:
---> 65 return self.cursor.execute(sql, params)
66
67 def executemany(self, sql, param_list):
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\backends\sq
lite3\base.py in execute(self, query, params)
326 return Database.Cursor.execute(self, query)
327 query = self.convert_query(query)
--> 328 return Database.Cursor.execute(self, query, params)
329
330 def executemany(self, query, param_list):
OperationalError: no such table: people_blogpost
In [3]: from people.models import Person
In [4]: Person.objects.create(name="WeizhongTu", age=24)
Out[4]: <Person: Person object>
In [5]: quit;
E:\ScienceSoft\Python\Django\learn_models>python manage.py shell
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AM
D64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from people.models import Person
In [2]: Person.objects.get(name="WeizhongTu")
---------------------------------------------------------------------------
MultipleObjectsReturned Traceback (most recent call last)
<ipython-input-2-4f81ae9bda54> in <module>()
----> 1 Person.objects.get(name="WeizhongTu")
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\mana
ger.py in manager_method(self, *args, **kwargs)
83 def create_method(name, method):
84 def manager_method(self, *args, **kwargs):
---> 85 return getattr(self.get_queryset(), name)(*args, **kwarg
s)
86 manager_method.__name__ = method.__name__
87 manager_method.__doc__ = method.__doc__
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\quer
y.py in get(self, *args, **kwargs)
382 raise self.model.MultipleObjectsReturned(
383 "get() returned more than one %s -- it returned %s!" %
--> 384 (self.model._meta.object_name, num)
385 )
386
MultipleObjectsReturned: get() returned more than one Person -- it returned 2!
In [3]: Person.objects.get(name="LiJun")
---------------------------------------------------------------------------
MultipleObjectsReturned Traceback (most recent call last)
<ipython-input-3-166e36314258> in <module>()
----> 1 Person.objects.get(name="LiJun")
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\mana
ger.py in manager_method(self, *args, **kwargs)
83 def create_method(name, method):
84 def manager_method(self, *args, **kwargs):
---> 85 return getattr(self.get_queryset(), name)(*args, **kwarg
s)
86 manager_method.__name__ = method.__name__
87 manager_method.__doc__ = method.__doc__
~\AppData\Local\Programs\Python\Python35\lib\site-packages\django\db\models\quer
y.py in get(self, *args, **kwargs)
382 raise self.model.MultipleObjectsReturned(
383 "get() returned more than one %s -- it returned %s!" %
--> 384 (self.model._meta.object_name, num)
385 )
386
MultipleObjectsReturned: get() returned more than one Person -- it returned 2!
In [4]: Person.objects.get(name="LiuYuan")
Out[4]: <Person: LiuYuan>
In [5]:
出現(xiàn)無法查詢數(shù)據(jù)的原因:
models.py:
from __future__ import unicode_literals
from django.db import models
from django.contrib import admin
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
# 在Python3中使用 def __str__(self):
return self.name
出現(xiàn)無法查詢數(shù)據(jù)的原因:
models.py中限次,如果是Python 3的版本,應(yīng)該要寫成def str(self):
而我寫成了 def unicode(self):
所以無法查詢數(shù)據(jù)浮驳,出現(xiàn)上述錯誤,即out[]:....
按 CTRL + C 退出當(dāng)前的 Python shell, 重復(fù)上面的操作捞魁,我們就可以看到:
from people.models import Person
In [4]: Person.objects.get(name="LiuYuan")
Out[4]: <Person: LiuYuan>
一旦使用all()方法至会,所有數(shù)據(jù)將會被刪除:
In [12]: Person.objects.all().delete()
Out[12]: (6, {'people.Person': 6})
In [13]: Person.objects.get(name="LiuYuan")
In [14]: Person.objects.create(name="YeZi", age=24)
Out[14]: <Person: YeZi>
In [15]: Person.objects.get(name="YeZi")
Out[15]: <Person: YeZi>
In [16]:
例如說我們現(xiàn)在想要將Sun的名稱由原來的”YeZi”更改為”Sun”。若使用save()方法谱俭,如:
In [16]: p = Person.objects.get(name='YeZi')
In [17]: p.name = 'Sun'
In [18]: p.save()
In [19]: Person.objects.get(name="Sun")
Out[19]: <Person: Sun>
如果沒有在models.py中增加以下語句奉件,則查詢結(jié)果中顯示<Person: Person object>宵蛀,這里并沒有顯示出與WeizhongTu的相關(guān)信息,如果用戶多了就無法知道查詢出來的到底是誰县貌,查詢結(jié)果是否正確
def __str__(self):
# 在Python3中使用 def __str__(self):
return self.name
七术陶、Django QuerySet API
Django 模型中我們學(xué)習(xí)了一些基本的創(chuàng)建與查詢。這里專門來講一下數(shù)據(jù)庫接口相關(guān)的接口(QuerySet API)煤痕,當(dāng)然您也可以選擇暫時跳過此節(jié)瞳别,如果以后用到數(shù)據(jù)庫相關(guān)的時候再看也是可以的。
從數(shù)據(jù)庫中查詢出來的結(jié)果一般是一個集合杭攻,這個集合叫做 QuerySet。
文中的例子大部分是基于這個 people/models.py
models.py:
from __future__ import unicode_literals
from django.db import models
from django.contrib import admin
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
# 在Python3中使用 def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
def __str__(self):
# __str__ on Python3
return self.name
class Entry(models.Model):
person = models.ForeginKey(Person)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __str__(self):
return self.headline
.QuerySet 創(chuàng)建對象的方法
將Person類改為Blog:
E:\ScienceSoft\Python\Django\learn_models>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, people, sessions
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won
't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage
.py migrate' to apply them.
E:\ScienceSoft\Python\Django\learn_models>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, people, sessions
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won
't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage
.py migrate' to apply them.
E:\ScienceSoft\Python\Django\learn_models>python manage.py makemigrations
Migrations for 'people':
people\migrations\0002_auto_20170724_1136.py
- Create model Author
- Create model Blog
- Create model Entry
- Delete model Person
E:\ScienceSoft\Python\Django\learn_models>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, people, sessions
Running migrations:
Applying people.0002_auto_20170724_1136... OK
E:\ScienceSoft\Python\Django\learn_models>
python manage.py shell
In [3]: from people.models import Blog
In [4]: b = Blog(name='LiJun Blog', tagline='The First Blog.')
In [5]: b.save()
2.創(chuàng)建對象
In [6]: Author.objects.create(name="Sky", email="121712221@qq.com")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-fd03139c84fe> in <module>()
----> 1 Author.objects.create(name="Sky", email="121712221@qq.com")
NameError: name 'Author' is not defined
In [7]: from people.models import Author
In [8]: Author.objects.create(name="Sky", email="121712221@qq.com")
Out[8]: <Author: Sky>
法二:
In [14]: a1 = Author(name="Rain", email="1198178812@qq.com")
In [15]: a1.save()
方法三:
In [16]: a2 = Author()
In [17]: a2.name="Snow"
In [18]: a2.email="1291819@qq.com"
In [19]: a2.save()
方法三:
In [20]: Author.objects.get_or_create(name="Bling", email="1190812312@qq.com")
Out[20]: (<Author: Bling>, True)
備注:前三種方法返回的都是對應(yīng)的 object疤坝,最后一種方法返回的是一個元組兆解,(object, True/False),創(chuàng)建時返回 True, 已經(jīng)存在時返回 False
當(dāng)有一對多跑揉,多對一锅睛,或者多對多的關(guān)系的時候,先把相關(guān)的對象查詢出來
保存外鍵和多對多關(guān)系的字段历谍,如下例子:
更新外鍵字段和普通的字段一樣现拒,只要指定一個對象的正確類型。
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()
更新多對多字段時又一點(diǎn)不太一樣望侈,使用add()方法添加相關(guān)聯(lián)的字段的值印蔬。
>> joe = Author.objects.create(name="Joe")
>> entry.authors.add(joe)
這是model,有blog脱衙,author侥猬,以及entry;其中entry分別與blog與author表關(guān) 聯(lián)捐韩,entry與blog表是通過 外鍵(models.ForeignKey())相連退唠,屬于一對多的關(guān)系,即一個entry對應(yīng)多個blog荤胁,entry與author是多對多的關(guān)系瞧预, 通過modles.ManyToManyField()實(shí)現(xiàn)。
In [29]: email = '1190812312@qq.com'
...: name = 'Bling'
...: try:
...: Author.objects.get(email=email):
...: except Author.DoesNotExist:
...: author = Author()
...: author.name = name
...: author.email = email
...: author.save()
...:
...:
File "<ipython-input-29-1078f61e74ac>", line 4
Author.objects.get(email=email):
^
SyntaxError: invalid syntax
In [30]: email = '1190812312@qq.com'
...: name = 'Bling'
...: try:
...: Author.objects.get(email=email)
...: except Author.DoesNotExist:
...: author = Author()
...: author.name = name
...: author.email = email
...: author.save()
...:
...:
In [31]:
matching query does not exist.
剛開始的代碼是這樣的仅政,group表在[數(shù)據(jù)庫](http://lib.csdn.net/base/mysql)中是空的
**[python]** [view plain](http://blog.csdn.net/python_tty/article/details/50930978#) [copy](http://blog.csdn.net/python_tty/article/details/50930978#)
<pre name="code" class="python">email = 'example@163.com'
name = 'develop'
if not Group.objects.get(email=email):
group = Group()
group.name = name
group.email = email
group.save()
這樣執(zhí)行代碼后垢油,一直報錯 matching query does not exist. 查了一下官方文檔,是使用get函數(shù)引起的錯誤已旧。使用get方法時秸苗,當(dāng)找不到匹配的query時,就會報DoesNotExist exception.代碼這樣改一下就可以了:
In [31]: cheese_blog = Author.objects.get(name="Sky")
所以DoesNotExist: Blog matching query does not exist.
IIn [27]: cheese_blog = Blog.objects.get(name="Sky")...異常是因?yàn)槲覜]有給類Blog插入數(shù)據(jù)
stackoverfolow給出的解決方法都是看手冊
下面附上手冊相關(guān)部分及我的翻譯运褪。
解決辦法就是其中提到的這句話:
如果你想要保存一個QuerySet的每一小項(xiàng)并確保每個實(shí)例都運(yùn)行save()命令惊楼,你不需要任何特別的函數(shù)玖瘸。你需要的是直接對其運(yùn)行循環(huán)語句并且發(fā)出save()命令。
for item in my_queryset: item.save()
******################**
附:手冊翻譯
****################****
[馬上升級多個objects](https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once)
有時候你想要為一個QuerySet里的所有objects設(shè)置一個特定值空間檀咙。你可以用update()方法雅倒。例如:
# Update all the headlines with pub_date in 2007.Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
用這個方法,你只能設(shè)置非關(guān)聯(lián)空間和ForeignKey空間弧可。升級非關(guān)聯(lián)空間蔑匣,請?zhí)峁┮粋€新取值作為恒值。升級ForeignKey空間棕诵,請設(shè)置一個新值升級你關(guān)注的新model裁良。
>>> b = Blog.objects.get(pk=1)# Change every Entry so that it belongs to this Blog.>>> Entry.objects.all().update(blog=b)
update()一旦使用立即生效并返回query對應(yīng)的行的數(shù)字(這些數(shù)字可能并不等于那些已經(jīng)擁有新值的行的數(shù)字)。被升級的QuerySet僅有的局限是它只能訪問一個[數(shù)據(jù)庫](http://lib.csdn.net/base/mysql)表格——model對應(yīng)的主表校套。你可以在相關(guān)聯(lián)控件的基礎(chǔ)上篩選价脾,但是你只能升級這個model的主表列。例如:
>>> b = Blog.objects.get(pk=1)# Update all the headlines belonging to this Blog.>>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
注意笛匙,upadate()是直接被翻譯成SQL命令的侨把。它是一系列用于直接升級的操作命令集。它并不對你的model運(yùn)行save()命令妹孙,也不發(fā)出pre_save或post_save信號(這些信號是由save()命令發(fā)出的)秋柄,也不會照顧到auto_now空間選項(xiàng)。如果你想要保存一個QuerySet的每一小項(xiàng)并確保每個實(shí)例都運(yùn)行save()命令蠢正,你不需要任何特別的函數(shù)骇笔。你需要的是直接對其運(yùn)行循環(huán)語句并且發(fā)出save()命令。
for item in my_queryset: item.save()
Calls to update can also use [F expressions
](https://docs.djangoproject.com/en/dev/ref/models/expressions/#django.db.models.F) to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value. For example, to increment the pingback count for every entry in the blog:
>>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
However, unlike F()
objects in filter and exclude clauses, you can’t introduce joins when you use F()
objects in an update – you can only reference fields local to the model being updated. If you attempt to introduce a join with an F()
object, a FieldError
will be raised:
# THIS WILL RAISE A FieldError>>> Entry.objects.update(headline=F('blog__name'))
[](http://blog.csdn.net/gavinking0110/article/details/53139559#)[](http://blog.csdn.net/gavinking0110/article/details/53139559#)[](http://blog.csdn.net/gavinking0110/article/details/53139559#)[](http://blog.csdn.net/gavinking0110/article/details/53139559#)[](http://blog.csdn.net/gavinking0110/article/details/53139559#)[](http://blog.csdn.net/gavinking0110/article/details/53139559#)
現(xiàn)在插入數(shù)據(jù):
八机隙、Django QuerySet 進(jìn)階
閱讀本文你可以學(xué)習(xí)到什么
查看 Django queryset 執(zhí)行的 SQL(1部分)
獲得的查詢結(jié)果直接以類似list方式展示(2蜘拉,3 部分)
如何在django中給一個字段取一個別名(4. 部分)
annotate 聚合 計數(shù),求和有鹿,求平均數(shù)等(5. 部分)
優(yōu)化SQL旭旭,減少多對一,一對多葱跋,多對多時查詢次數(shù)(6持寄,7 部分)
如何只取出需要的字段,排除某些字段(8娱俺,9部分)
自定義一個自定義聚合功能稍味,比如 group_concat(10. 部分)
1.新建一個項(xiàng)目 zqxt ,建一個 app 名稱是 blog
2.把 blog 加入到 settings.py 中的 INSTALL_APPS 中
settings.py:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#
'blog',
]
blog/models.py:
from django.db import models
# Create your models here.
from __future__ import unicode_literals
from django.utils.encoding import python_3_unicode_compatible
calss Author(models.Model):
name = models.CharField(max_length=50)
qq = models.CharField(max_length=10)
addr = models.TextField()
email = models.EmailField()
def __str__(self):
return self.name
class Article(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(Author)
content = models.TextField()
score = models.IntegerField()
tags = models.ManyToManyField('Tag')
def __str__(self):
return self.title
class Tag(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
比較簡單荠卷,假設(shè)一篇文章只有一個作者(Author)模庐,一個作者可以有多篇文章(Article),一篇文章可以有多個標(biāo)簽(Tag)油宜。
創(chuàng)建 migrations 然后 migrate 在數(shù)據(jù)庫中生成相應(yīng)的表
E:\ScienceSoft\Python\Django\project4>python manage.py makemigrations
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model Article
- Create model Author
- Create model Tag
- Add field author to article
- Add field tags to article
E:\ScienceSoft\Python\Django\project4>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying blog.0001_initial... OK
Applying sessions.0001_initial... OK
創(chuàng)建initdb.py,并運(yùn)行:initdb.py是什么文件_百度知道
3個答案 -
最佳答案.py是python的腳本文件后綴掂碱。initdb土涝,看名稱是初始化數(shù)據(jù)庫的文件名愁茁。所以姆打,應(yīng)該是一個初始化數(shù)據(jù)庫的python腳本文件鲫懒。
E:\ScienceSoft\Python\Django>django-admin startproject project4
E:\ScienceSoft\Python\Django>python manage.py startapp blog
python: can't open file 'manage.py': [Errno 2] No such file or directory
E:\ScienceSoft\Python\Django>cd project4
E:\ScienceSoft\Python\Django\project4>python manage.py startapp blog
E:\ScienceSoft\Python\Django\project4>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\core\management\__init__.py", line 363, in execute_from_command_l
ine
utility.execute()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\core\management\__init__.py", line 337, in execute
django.setup()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\apps\registry.py", line 108, in populate
app_config.import_models()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\import
lib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 658, in exec_module
File "<frozen importlib._bootstrap_external>", line 764, in get_code
File "<frozen importlib._bootstrap_external>", line 724, in source_to_code
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "E:\ScienceSoft\Python\Django\project4\blog\models.py", line 8
calss Author(models.Model):
^
SyntaxError: invalid syntax
E:\ScienceSoft\Python\Django\project4>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\core\management\__init__.py", line 363, in execute_from_command_l
ine
utility.execute()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\core\management\__init__.py", line 337, in execute
django.setup()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\apps\registry.py", line 108, in populate
app_config.import_models()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\import
lib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 658, in exec_module
File "<frozen importlib._bootstrap_external>", line 764, in get_code
File "<frozen importlib._bootstrap_external>", line 724, in source_to_code
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "E:\ScienceSoft\Python\Django\project4\blog\models.py", line 4
from __future__ import unicode_literals
^
SyntaxError: from __future__ imports must occur at the beginning of the file
E:\ScienceSoft\Python\Django\project4>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\core\management\__init__.py", line 363, in execute_from_command_l
ine
utility.execute()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\core\management\__init__.py", line 337, in execute
django.setup()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\apps\registry.py", line 108, in populate
app_config.import_models()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\import
lib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "E:\ScienceSoft\Python\Django\project4\blog\models.py", line 7, in <modul
e>
from django.utils.encoding import python_3_unicode_compatible
ImportError: cannot import name 'python_3_unicode_compatible'
E:\ScienceSoft\Python\Django\project4>python manage.py makemigrations
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model Article
- Create model Author
- Create model Tag
- Add field author to article
- Add field tags to article
E:\ScienceSoft\Python\Django\project4>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying blog.0001_initial... OK
Applying sessions.0001_initial... OK
E:\ScienceSoft\Python\Django\project4>python initdb.py
python: can't open file 'initdb.py': [Errno 2] No such file or directory
E:\ScienceSoft\Python\Django\project4>python initdb.py
File "initdb.py", line 16
author.qq = ''.join(
^
IndentationError: unexpected indent
E:\ScienceSoft\Python\Django\project4>python initdb.py
Traceback (most recent call last):
File "initdb.py", line 4, in <module>
from blog.models import Author, Article, Tag
File "E:\ScienceSoft\Python\Django\project4\blog\models.py", line 9, in <modul
e>
class Author(models.Model):
File "E:\ScienceSoft\Python\Django\project4\blog\models.py", line 11, in Autho
r
name = models.CharField(max_length=50)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\db\models\fields\__init__.py", line 1061, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\db\models\fields\__init__.py", line 172, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\conf\__init__.py", line 56, in __getattr__
self._setup(name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\conf\__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.
E:\ScienceSoft\Python\Django\project4>python initdb.py
Traceback (most recent call last):
File "initdb.py", line 4, in <module>
from blog.models import Author, Article, Tag
File "E:\ScienceSoft\Python\Django\project4\blog\models.py", line 9, in <modul
e>
class Author(models.Model):
File "E:\ScienceSoft\Python\Django\project4\blog\models.py", line 11, in Autho
r
name = models.CharField(max_length=50)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\db\models\fields\__init__.py", line 1061, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\db\models\fields\__init__.py", line 172, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\conf\__init__.py", line 56, in __getattr__
self._setup(name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\conf\__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.
E:\ScienceSoft\Python\Django\project4>python initdb.py
Traceback (most recent call last):
File "initdb.py", line 15, in <module>
class Author(models.Model):
File "initdb.py", line 16, in Author
name = models.CharField(max_length=50)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\db\models\fields\__init__.py", line 1061, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\db\models\fields\__init__.py", line 172, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\conf\__init__.py", line 56, in __getattr__
self._setup(name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-p
ackages\django\conf\__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.
E:\ScienceSoft\Python\Django\project4>python initdb.py
File "initdb.py", line 4
from __future__ import unicode_literals
^
SyntaxError: from __future__ imports must occur at the beginning of the file
E:\ScienceSoft\Python\Django\project4>python initdb.py
File "initdb.py", line 70
from __future__ import unicode_literals
^
SyntaxError: from __future__ imports must occur at the beginning of the file
E:\ScienceSoft\Python\Django\project4>python initdb.py
Traceback (most recent call last):
File "initdb.py", line 61, in <module>
main()
File "initdb.py", line 57, in main
create_articles_and_tags()
File "initdb.py", line 33, in create_articles_and_tags
for article_title in article_titlr_list:
NameError: name 'article_titlr_list' is not defined
E:\ScienceSoft\Python\Django\project4>python initdb.py
Traceback (most recent call last):
File "initdb.py", line 61, in <module>
main()
File "initdb.py", line 57, in main
create_articles_and_tags()
File "initdb.py", line 36, in create_articles_and_tags
tag_name = article_title.spilt(' ', 1)[0]
AttributeError: 'str' object has no attribute 'spilt'
E:\ScienceSoft\Python\Django\project4>python initdb.py
Done!
E:\ScienceSoft\Python\Django\project4>
在[Python](http://lib.csdn.net/base/python)的開發(fā)中,遇到了這個錯誤: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. 解決方法如下: 在代碼文件的最上方醉者,添加如下代碼:
import os,djangoos.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")# project_name 項(xiàng)目名稱django.setup()
最終的initdb.py代碼如下:
from __future__ import unicode_literals
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project4.settings")# project_name 項(xiàng)目名稱
django.setup()
import random
from project4 import *
from blog.models import Author, Article, Tag
author_name_list = ['Sky', 'Rain', 'Snow', 'Bling', 'Flowers']
article_title_list = ['Django 教程', 'Python 教程', 'HTML 教程']
def create_authors():
for author_name in author_name_list:
author, created = Author.objects.get_or_create(name=author_name)
# 隨機(jī)生成9位數(shù)的QQ但狭,
author.qq = ''.join(
str(random.choice(range(10))) for _ in range(9)
)
author.addr = 'addr_%s' % (random.randrange(1, 3))
author.email = '%s@skyrain.com' % (author.addr)
author.save()
def create_articles_and_tags():
# 隨機(jī)生成文章
for article_title in article_title_list:
# 從文章標(biāo)題中得到 tag
tag_name = article_title.split(' ', 1)[0]
tag, created = Tag.objects.get_or_create(name=tag_name)
random_author = random.choice(Author.objects.all())
for i in range(1, 21):
title = '%s_%s' % (article_title, i)
article, created = Article.objects.get_or_create(
title=title, defaults={
'author': random_author,
'content': '%s 正文 ' % title,
'score': random.randrange(70, 101),
}
)
article.tags.add(tag)
def main():
create_authors()
create_articles_and_tags()
if __name__ == '__main__':
main()
print("Done!")
運(yùn)行結(jié)果:
E:\ScienceSoft\Python\Django\project4>python initdb.py
Done!
導(dǎo)入數(shù)據(jù)后,我們確認(rèn)一下數(shù)據(jù)是不是已經(jīng)導(dǎo)入撬即。
In [1]: from blog.models import Article, Author, Tag
In [2]: Article.objects.all()
Out[2]: <QuerySet [<Article: Django 教程_1>, <Article: Django 教程_2>, <Article:
Django 教程_3>, <Article: Django 教程_4>, <Article: Django 教程_5>, <Article: D
jango 教程_6>, <Article: Django 教程_7>, <Article: Django 教程_8>, <Article: Dja
ngo 教程_9>, <Article: Django 教程_10>, <Article: Django 教程_11>, <Article: Dja
ngo 教程_12>, <Article: Django 教程_13>, <Article: Django 教程_14>, <Article: Dj
ango 教程_15>, <Article: Django 教程_16>, <Article: Django 教程_17>, <Article: D
jango 教程_18>, <Article: Django 教程_19>, <Article: Django 教程_20>, '...(remai
ning elements truncated)...']>
In [3]:
In [3]: Author.objects.all()
Out[3]: <QuerySet [<Author: Sky>, <Author: Rain>, <Author: Snow>, <Author: Bling
>, <Author: Flowers>]>
In [4]: Tag.objects.all()
Out[4]: <QuerySet [<Tag: Django>, <Tag: Python>, <Tag: HTML>]>
我們開始正式本節(jié)的學(xué)習(xí)立磁,學(xué)習(xí)一些比較高級的查詢方法
- 查看 Django queryset 執(zhí)行的 SQL