Django ——自強學堂學習筆記2

新手求助,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]:

出現無法查詢數據的原因:
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

出現無法查詢數據的原因:
models.py中,如果是Python 3的版本,應該要寫成def str(self):
而我寫成了 def unicode(self):
所以無法查詢數據,出現上述錯誤,即out[]:....
按 CTRL + C 退出當前的 Python shell, 重復上面的操作,我們就可以看到:

from people.models import Person
In [4]: Person.objects.get(name="LiuYuan")
Out[4]: <Person: LiuYuan>
一旦使用all()方法,所有數據將會被刪除:
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]:

例如說我們現在想要將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中增加以下語句,則查詢結果中顯示<Person: Person object>,這里并沒有顯示出與WeizhongTu的相關信息,如果用戶多了就無法知道查詢出來的到底是誰,查詢結果是否正確

def __str__(self):
        # 在Python3中使用 def __str__(self):
        return self.name

七、Django QuerySet API
Django 模型中我們學習了一些基本的創建與查詢。這里專門來講一下數據庫接口相關的接口(QuerySet API),當然您也可以選擇暫時跳過此節,如果以后用到數據庫相關的時候再看也是可以的。
從數據庫中查詢出來的結果一般是一個集合,這個集合叫做 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 創建對象的方法
將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.創建對象

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)

備注:前三種方法返回的都是對應的 object,最后一種方法返回的是一個元組,(object, True/False),創建時返回 True, 已經存在時返回 False

當有一對多,多對一,或者多對多的關系的時候,先把相關的對象查詢出來

保存外鍵和多對多關系的字段,如下例子: 
更新外鍵字段和普通的字段一樣,只要指定一個對象的正確類型。 
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk") 
>>> entry.blog = cheese_blog 
>>> entry.save() 

更新多對多字段時又一點不太一樣,使用add()方法添加相關聯的字段的值。 
>> joe = Author.objects.create(name="Joe") 
>> entry.authors.add(joe) 
這是model,有blog,author,以及entry;其中entry分別與blog與author表關 聯,entry與blog表是通過 外鍵(models.ForeignKey())相連,屬于一對多的關系,即一個entry對應多個blog,entry與author是多對多的關系, 通過modles.ManyToManyField()實現。
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表在[數據庫](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()   

這樣執行代碼后,一直報錯 matching query does not exist. 查了一下官方文檔,是使用get函數引起的錯誤。使用get方法時,當找不到匹配的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")...異常是因為我沒有給類Blog插入數據
stackoverfolow給出的解決方法都是看手冊
下面附上手冊相關部分及我的翻譯。
解決辦法就是其中提到的這句話:

如果你想要保存一個QuerySet的每一小項并確保每個實例都運行save()命令,你不需要任何特別的函數。你需要的是直接對其運行循環語句并且發出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設置一個特定值空間。你可以用update()方法。例如:
# Update all the headlines with pub_date in 2007.Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')

用這個方法,你只能設置非關聯空間和ForeignKey空間。升級非關聯空間,請提供一個新取值作為恒值。升級ForeignKey空間,請設置一個新值升級你關注的新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對應的行的數字(這些數字可能并不等于那些已經擁有新值的行的數字)。被升級的QuerySet僅有的局限是它只能訪問一個[數據庫](http://lib.csdn.net/base/mysql)表格——model對應的主表。你可以在相關聯控件的基礎上篩選,但是你只能升級這個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運行save()命令,也不發出pre_save或post_save信號(這些信號是由save()命令發出的),也不會照顧到auto_now空間選項。如果你想要保存一個QuerySet的每一小項并確保每個實例都運行save()命令,你不需要任何特別的函數。你需要的是直接對其運行循環語句并且發出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#)

現在插入數據:

Django QuerySet API重看

八、Django QuerySet 進階
閱讀本文你可以學習到什么

  1. 查看 Django queryset 執行的 SQL(1部分)

  2. 獲得的查詢結果直接以類似list方式展示(2,3 部分)

  3. 如何在django中給一個字段取一個別名(4. 部分)

  4. annotate 聚合 計數,求和,求平均數等(5. 部分)

  5. 優化SQL,減少多對一,一對多,多對多時查詢次數(6,7 部分)

  6. 如何只取出需要的字段,排除某些字段(8,9部分)

  7. 自定義一個自定義聚合功能,比如 group_concat(10. 部分)
    1.新建一個項目 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

比較簡單,假設一篇文章只有一個作者(Author),一個作者可以有多篇文章(Article),一篇文章可以有多個標簽(Tag)。

創建 migrations 然后 migrate 在數據庫中生成相應的表

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

創建initdb.py,并運行:initdb.py是什么文件_百度知道
3個答案 -
最佳答案.py是python的腳本文件后綴。initdb,看名稱是初始化數據庫的文件名。所以,應該是一個初始化數據庫的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)的開發中,遇到了這個錯誤: 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 項目名稱django.setup()

最終的initdb.py代碼如下:

from __future__ import unicode_literals
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project4.settings")# project_name 項目名稱
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)
         # 隨機生成9位數的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():
    # 隨機生成文章

    for article_title in article_title_list:
        # 從文章標題中得到 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!")
運行結果:
E:\ScienceSoft\Python\Django\project4>python initdb.py
Done!

導入數據后,我們確認一下數據是不是已經導入。

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>]>

我們開始正式本節的學習,學習一些比較高級的查詢方法

  1. 查看 Django queryset 執行的 SQL
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,702評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,143評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,553評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,620評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,416評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,940評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,024評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,170評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,709評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,597評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,784評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,291評論 5 357
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,029評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,407評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,663評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,403評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,746評論 2 370

推薦閱讀更多精彩內容