- Models
- Fileds
- Meta options
- Model attributes
- Model methods
- Model inheritance
- Making queries
- Aggregation
- Search
- Managers
- Performing raw SQL queries
- Database transactions
- Multiple databases
- Tablespaces
- Database access optimization
- Database instrumentation
- Examples of model relationship API usage
-
-
Save amelieykw/a536aab1aef040c16682439be83bbf88 to your computer and use it in GitHub Desktop.
Each model maps to a single database table.
This example model defines a Person, which has a first_name and last_name:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
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
idfield is added automatically, but this behavior can be overridden. See Automatic primary key fields.
For example, if you have an app bookstore (as created by manage.py startapp bookstore), a model defined as class Book will have a database table named bookstore_book.
To override the database table name, use the db_table parameter in class Meta.
Use lowercase table names for MySQL
It is strongly advised that you use lowercase table names when you override the table name via
db_table, particularly if you are using the MySQL backend. See the MySQL notes for more details.
- define your models
- tell Django to use those models
- editing your settings file
- change the INSTALLLED_APPS setting to add the name of the module that contains your models.py
- if the models for your app live in the module myapp.models, the INSTALLLED_APPS should read:
INSTALLED_APPS = [ #... 'myapp', #... ]
- When you add new apps to INSTALLED_APPS, be sure to run
manage.py migrate, optionally making migrations for them first withmanage.py makemigrations.
- Creating Objects
- Saving changes to objects
- Retriving objects
- Complex lookups with Q objects
- Comparing objects
- Deleting objects
- Copying model instance
- Updating multiple objects at once
- Ralated objects
- One-to-many relationship
- Many-to-many relationship
- One-to-one relationship
- Falling back to raw SQL
- A model class = a database table
- an instance of that class = a particular record in the database table
- To create an object, instantiate it using keyword arguments to the model class, then call
save()to save it to the database.
- To create an object, instantiate it using keyword arguments to the model class, then call
# mysite/blog/models.py
>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()
This performs an INSERT SQL statement behind the scenes.
Django doesn’t hit the database until you explicitly call save().
The save() method has no return value.
Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)[source]
>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b2.id # Returns None, because b doesn't have an ID yet.
>>> b2.save()
>>> b2.id # Returns the ID of your new object.
create(**kwargs)
A convenience method for creating an object and saving it all in one step.
p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
and
p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)
are equivalent.
The force_insert parameter is documented elsewhere, but all it means is that a new object will always be created. Normally you won’t need to worry about this. However, if your model contains a manual primary key value that you set and if that value already exists in the database, a call to create() will fail with an IntegrityError since primary keys must be unique. Be prepared to handle the exception if you are using manual primary keys.
To save changes to an object that’s already in the database, use save().
Given a Blog instance b5 that has already been saved to the database, this example changes its name and updates its record in the database:
>>> b5.name = 'New name'
>>> b5.save()
This performs an UPDATE SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save().
Updating a ForeignKey field works exactly the same way as saving a normal field – simply assign an object of the right type to the field in question.
This example updates the blog attribute of an Entry instance entry, assuming appropriate instances of Entry and Blog are already saved to the database (so we can retrieve them below):
>>> from blog.models import Blog, Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()
Updating a ManyToManyField works a little differently – use the add() method on the field to add a record to the relation.
This example adds the Author instance joe to the entry object:
>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)
To add multiple records to a ManyToManyField in one go, include multiple arguments in the call to add(), like this:
>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)
-
Person.objects.create(name=name,age=age)
p = Person(name="WZ", age=23)
p.save()
p = Person(name="TWZ")
p.age = 23
p.save()
Person.objects.get_or_create(name="WZT", age=23)
-
Person.objects.all() -
Person.objects.all()[:10]切片操作,获取10个人,不支持负索引,切片可以节约内存 -
Person.objects.get(name=name)
get是用来获取一个对象的,如果需要获取满足条件的一些人,就要用到filter
-
Person.objects.filter(name="abc")# 等于Person.objects.filter(name__exact="abc") 名称严格等于 "abc" 的人 -
Person.objects.filter(name__iexact="abc")# 名称为 abc 但是不区分大小写,可以找到 ABC, Abc, aBC,这些都符合条件 -
Person.objects.filter(name__contains="abc")# 名称中包含 "abc"的人 -
Person.objects.filter(name__icontains="abc")#名称中包含 "abc",且abc不区分大小写 -
Person.objects.filter(name__regex="^abc")# 正则表达式查询 -
Person.objects.filter(name__iregex="^abc")# 正则表达式不区分大小写
filter是找出满足条件的,当然也有排除符合某条件的
-
Person.objects.exclude(name__contains="WZ")# 排除包含 WZ 的Person对象 -
Person.objects.filter(name__contains="abc").exclude(age=23)# 找出名称含有abc, 但是排除年龄是23岁的
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:
>>> 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."
Note
Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations.
The Manager is the main source of QuerySets for a model. For example, Blog.objects.all() returns a QuerySet that contains all Blog objects in the database.
retrieve objects from a table is to get all of them
all_entries = Entry.objects.all()
The all() method returns a QuerySet of all the objects in the database.
The QuerySet returned by all() describes all objects in the database table. Usually, though, you’ll need to select only a subset of the complete set of objects.
To create such a subset, you refine the initial QuerySet, adding filter conditions.
The two most common ways to refine a QuerySet are:
Returns a new QuerySet containing objects that match the given lookup parameters.
Returns a new QuerySet containing objects that do not match the given lookup parameters.
For example, to get a QuerySet of blog entries from the year 2006, use filter() like so:
Entry.objects.filter(pub_date__year=2006)
With the default manager class, it is the same as:
Entry.objects.all().filter(pub_date__year=2006)
>>> Entry.objects.filter(
... headline__startswith='What'
... ).exclude(
... pub_date__gte=datetime.date.today()
... ).filter(
... pub_date__gte=datetime.date(2005, 1, 30)
... )
This takes the initial QuerySet of all entries in the database, adds a filter, then an exclusion, then another filter. The final result is a QuerySet containing all entries with a headline that starts with “What”, that were published between January 30, 2005, and the current day.
Each time you refine a QuerySet, you get a brand-new QuerySet that is in no way bound to the previous QuerySet. Each refinement creates a separate and distinct QuerySet that can be stored, used and reused.
>>> q1 = Entry.objects.filter(headline__startswith="What")
>>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
>>> q3 = q1.filter(pub_date__gte=datetime.date.today())
These three QuerySets are separate. The first is a base QuerySet containing all entries that contain a headline starting with “What”. The second is a subset of the first, with an additional criteria that excludes records whose pub_date is today or in the future. The third is a subset of the first, with an additional criteria that selects only the records whose pub_date is today or in the future. The initial QuerySet (q1) is unaffected by the refinement process.
QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity.
You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated.
Take a look at this example:
>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.date.today())
>>> q = q.exclude(body_text__icontains="food")
>>> print(q)
Though this looks like three database hits, in fact it hits the database only once, at the last line (print(q)).
In general, the results of a QuerySet aren’t fetched from the database until you “ask” for them. When you do, the QuerySet is evaluated by accessing the database.
filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.
If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly:
>>> one_entry = Entry.objects.get(pk=1)
You can use any query expression with get(), just like with filter().
Note that there is a difference between using get(), and using filter() with a slice of [0].
If there are no results that match the query, get() will raise a DoesNotExist exception. This exception is an attribute of the model class that the query is being performed on - so in the code above, if there is no Entry object with a primary key of 1, Django will raise Entry.DoesNotExist.
The "Cuddles" https://www.jerkroulette.com/blog/cuddles blog explores the importance of physical touch and affection in relationships. It discusses how cuddling can strengthen bonds and improve well-being, transitioning from cozy embraces to more electrifying intimacy. The guide covers various forms of cuddles, from flirtatious foreplay to uninhibited mutual pleasure, and how to harness privacy and technology to deepen that delicious sense of connection.