西维蜀黍

【Django】template - 插入 Python 代码

if/else 标签

基本语法格式如下:

{% if condition %}
   ... display
{% endif %}

或者:

{% if condition1 %}
   ... display 1
{% elif condiiton2 %}
   ... display 2
{% else %}
   ... display 3
{% endif %}

根据条件判断是否输出。if/else 支持嵌套。

Note:模板标签中的变量是不需要用 {% raw %}{{ {% endraw %} 来包裹的。

and、or 或not

{% raw %}{% if %}{% endraw %} 标签接受 and , or 或者 not 关键字来对多个变量做判断 ,或者对变量取反(not),例如:

{% if athlete_list and coach_list %}
     athletes 和 coaches 变量都是可用的。
{% endif %}

注意,{% raw %}{% if %}{% endraw %} 标签不允许在同一个标签中同时使用 and 和 or ,因为逻辑上可能模糊的,这样的代码是不合法的:

{% if athlete_list and coach_list or cheerleader_list %}

系统不支持用圆括号来组合比较操作。 如果你确实需要用到圆括号来组合表达你的逻辑式,考虑将它移到模板之外处理,然后以模板变量的形式传入结果吧。 或者,仅仅用嵌套的 {% raw %}{% if %}{% endraw %} 标签替换

  ...


【Django】Django ORM - QuerySet 序列化

最完美的方法

解决:

  • ‘dict’ object has no attribute ‘_meta’
  • Queryset is not JSON serializable
users = models.User.objects.values(*USER_FIELDS).filter(**filter)[start_index:start_index + limit]
if type(resp) is not list:
   resp = list(resp)
return HttpResponse(json.dumps(resp, indent=2, cls=DjangoJSONEncoder), content_type="application/json")
  ...


【Django】Django ORM - 查询数据

exclude()

Calling filter() again on a queryset clones it and adds new parameters with an AND operator. Note that multiple keyword parameters can be specified in a single function call.

Conversely, exclude() clones a queryset and adds any new parameters with an AND NOT operator:

>>> queryset = Employee.objects.filter(first_name="Roger", age=27)
>>> queryset2 = queryset.filter(last_name="Jolly")
>>> queryset3 = queryset.exclude(last_name="Jolly")
>>> any(employee.first_name != "Roger" for employee in queryset2)False
>>> any(employee.last_name != "Jolly" for employee in queryset2)False
>>> all(employee.last_name != "Jolly" for employee in queryset3)True

To retrieve all objects in the table with no parameters, use the all() function instead of filter(). all() can also be used to create a clone of an existing queryset (more on this later).

Iterating through querysets exposes the query results as instances of the associated Model.

  ...


【Django】Django ORM - CRUD

Retrieve

Retrieving Objects - get()

To retrieve objects from your database, construct a QuerySet via a Manager on your model class.

A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT.

You get a QuerySet by using your model’s Manager. Each model has at least one Manager, and it’s called objects by default. Access it directly via the model class, like so:

# Import the models we created from our "news" app
>>> from news.models import Article, Reporter

>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name='Foo', tagline='Bar')
>>> b.objects
Traceback:
    ...
AttributeError: "Manager isn't accessible via Blog instances."

get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.

get() raises a DoesNotExist exception if an object wasn’t found for the given parameters. This exception is an attribute of the model class. Example:

Entry.objects.get(id='foo') # raises Entry.DoesNotExist

The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist, so you can target multiple DoesNotExist exceptions. Example:

from django.core.exceptions import ObjectDoesNotExist
try:
    e = Entry.objects.get(id=3)
    b = Blog.objects.get(id=1)
except ObjectDoesNotExist:
    print("Either the entry or blog doesn't exist.")
  ...


【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']
  ...