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阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容