西维蜀黍

【Django】Django ORM - Define Model

Define Models

Quick example

Although you can use Django without a database, it comes with an object-relational mapper in which you describe your database layout in Python code.

The data-model syntax offers many rich ways of representing your models – so far, it’s been solving many years’ worth of database-schema problems.

Here’s a quick example:

#[app name]/models.py
from django.db import models

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __str__(self):
        return self.full_name

class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.

The above Person model would create a database table like this:

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

Some technical notes:

  • The name of the table, myapp_person, is automatically derived from some model metadata but can be overridden. See Table names for more details.
  • An id field is added automatically, but this behavior can be overridden. See Automatic primary key fields.
  • The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it’s worth noting Django uses SQL tailored to the database backend specified in your settings file.
  ...


【macOS】清除 DNS 缓存

sudo killall -HUP mDNSResponder; sleep 2; echo macOS DNS Cache Reset | say

Reference

  ...


【Django】错误汇总

Reason: image not found

Problem

通过 python manage.py runserver 0.0.0.0:80 启动 Django 时,报错:

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Working/my_project/venv/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: /usr/local/opt/mysql@5.7/lib/libmysqlclient.20.dylib
  Referenced from: /Working/my_project/venv/lib/python2.7/site-packages/_mysql.so
  Reason: image not found
Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x10acf42d8>

Solution

这其实是因为在启动 Django 时,python interpreter 为了连接 MySQL,需要 libmysqlclient.20.dylib 文件,而去 /usr/local/opt/mysql@5.7/lib/libmysqlclient.20.dylib 路径下找时,未找到该文件。

而事实上,本机中其实有 libmysqlclient.20.dylib 文件的,我的这个文件位于 /usr/local/mysql-5.7.28-macos10.14-x86_64/lib/libmysqlclient.20.dylib 下。

# 直接创建软链接,有可能会出现因不存在特定文件夹,导致创建失败的情况
$ sudo ln -s /usr/local/mysql-5.7.28-macos10.14-x86_64/lib/libmysqlclient.20.dylib /usr/local/opt/mysql@5.7/lib/libmysqlclient.20.dylib
ln: /usr/local/opt/mysql@5.7/lib/libmysqlclient.20.dylib: No such file or directory

$ mkdir /usr/local/opt/mysql@5.7
$ cd /usr/local/opt/mysql@5.7
$ mkdir lib
$ sudo ln -s /usr/local/mysql-5.7.28-macos10.14-x86_64/lib/libmysqlclient.20.dylib /usr/local/opt/mysql@5.7/lib/libmysqlclient.20.dylib

再次启动 Django 时,一切正常。

  ...


【Python】前缀

u - Unicode 字符串

Python 中定义一个 Unicode 字符串和定义一个普通字符串一样简单:

>>> u'Hello World !'
u'Hello World !'

引号前小写的"u"表示这里创建的是一个 Unicode 字符串。如果你想加入一个特殊字符,可以使用 Python 的 Unicode-Escape 编码。如下例所示:

>>> u'Hello\u0020World !'
u'Hello World !'

被替换的 \u0020 标识表示在给定位置插入编码值为 0x0020 的 Unicode 字符(空格符)。

其实,\u后面跟四个十六进制数,就可以代表一个Unicode字符。

  ...


【MySQL】MySQL Troubleshooting

Your password has expired.

Description: Your password has expired. To log in you must change it using a client that supports expired passwords.

  ...


【Python】Comprehensions

Comprehensions

要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11))

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

但如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环:

>>> L = []
>>> for x in range(1, 11):
...    L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的list:

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来。

for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:

>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

还可以使用两层循环,可以生成全排列:

>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
  ...


【Python】I/O - 输入

input()

>>>a = input("input:")
input:123                  # 输入整数
>>> type(a)
<type 'int'>               # 整型
>>> a = input("input:")    
input:"runoob"           # 正确,字符串表达式
>>> type(a)
<type 'str'>             # 字符串
>>> a = input("input:")
input:runoob               # 报错,不是表达式
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'runoob' is not defined
<type 'str'>

raw_input() - 将所有输入作为字符串看待

>>>a = raw_input("input:")
input:123
>>> type(a)
<type 'str'>              # 字符串
>>> a = raw_input("input:")
input:runoob
>>> type(a)
<type 'str'>              # 字符串
>>>
  ...


【Python】Python 一切皆对象

Python的一等公民

Python 中的一等公民,都具有以下特性:

  • 可以赋值给一个变量
  • 可以添加到集合对象中
  • 可以作为参数传递给函数
  • 可以当做函数的返回值

针对赋值给变量及添加到集合对象中,代码予以展示:

def func():
    print 'the func function is executed'


class Test:
    def __init__(self):
        print 'An instance of Test class is initialized'

obj_list = []
obj_list.append(func)
obj_list.append(Test)

for item in obj_list:							# 添加至集合对象中
    print(item())
  ...


【Python】Basics - Built-in Function(内置函数)

range() - 生成 list

Using only one argument in range()

print("Print first 5 numbers using range function")
for i in range(5):
    print(i, end=', ')

Output:

Print first 5 numbers using range function
0, 1, 2, 3, 4,

要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11))

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  ...


【Python】String

String 格式化

在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'

你可能猜到了,%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

常见的占位符有:

占位符 替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数
  ...