西维蜀黍

【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 时,一切正常。

  ...