Models and databases in Django are no stranger to the database, but how do Models understand them? The official documents contain the following sentence: Amodelisthesingle, definitivesourceofdataaboutyourdata. itcontainstheesstialfieldsandbehaviorsofthedatayo
Models and databases in Django are no stranger to everyone, but how do Models understand them? the official document provides the following sentence: A model is the single, definitive source of data about your data. it contains the essential fields and behaviors of thedata yo
Models and databases in Django)
Everyone is familiar with databases, But how should Models understand them? The official documents include the following sentence:
A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of thedata you're storing. Generally, each model maps to a single database table.
For the moment, Models is called "model" (Personal Name)
The model has the following three features:
Each model is a python subclass. Inherit from django. db. models. each attribute of the Model represents a database field except for the preceding, jango also provides an API for Automatically Generating database access. To facilitate understanding, let's take an example. In the following example, we create a Person model with two fields) first_name, last_name
From django. db import modelsclass Person (models. model): first_name = models. charField (max_length = 30) last_name = models. charField (max_length = 30) first_name and last_name are the fields of the Person model. Each Field is a specified class attribute, and each attribute is mapped to no column in the database.
Here I have a question: can a Field be called a Field?
The above Person model will correspond to 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); let's talk about it. Once you declare a models, you need to tell jango that you will use this models, add your application name to INSTALLED_APPS in your settings = (#... 'myapp ',#...) after you add a new application to INSTALLED_APPS, You need to execute manage. py migrate
Let's talk about Fields.
It is an important part of the model. It defines the fields of the database table from django. db import modelsclass Musician (models. model): first_name = models. charField (max_length = 50) last_name = models. charField (max_length = 50) instrument = models. charField (max_length = 100) class Album (models. model): artist = models. foreignKey (Musician) name = models. charField (max_length = 100) release_date = models. dateField () num_stars = models. in the IntegerField () model, each field is Field class instance, jango determines several points through the Field class type. 1. database field Type 2. When using the default HTML part but rendering the form field (e.g.,) Field optionEach Field has a specific parameter, such as CharField and max_lengthnull. If it is true, jango will store null values in the database. By default, it is falseblank. If it is true, field will allow space input, the default value is falsechoices. If choices is used in field, the HTML component displayed on the front end is
For example
YEAR_IN_SCHOOL_CHOICES = ((’FR’, ’Freshman’),(’SO’, ’Sophomore’),(’JR’, ’Junior’),(’SR’, ’Senior’),(’GR’, ’Graduate’),)from django.db import modelsclass Person(models.Model): SHIRT_SIZES = ( (’S’, ’Small’), (’M’, ’Medium’), (’L’, ’Large’), ) name = models.CharField(max_length=60) shirt_size = models.CharField(max_length=1,choices=SHIRT_SIZES)>>> p = Person(name="Fred Flintstone", shirt_size="L")>>> p.save()>>> p.shirt_sizeu’L’>>> p.get_shirt_size_display()u’Large’
Save ()
This execution executes an insert SQL statement in the background. However, no real Database Import knows that the user executes save () and save () does not return values, but save () supports parameters.
Model.save ([force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None] )
When you perform the save () operation, jango performs the following steps:
-
1: trigger the pre-save event. This signal can be listened to by any function.
-
2: Some fields with special field types for processing, such as dateField and auto_now = True. The value obtained at this time is the time jango was generated. Note that, the database time may be different from the server time, so pay attention to time synchronization.
-
3: Prepare data for insertion. Each field provides a processed value.
-
4: Prepare an SQL statement for insertion. Here I understand it as a spelling SQL statement.
-
5: Send the SQL statement to the database
All ()
All_entries = Entry. objects. all () view all the content filters (** kwargs). Now let's take a look at getting the specific value Entry through the filter (filters. objects. filter (pub_date _ year = 2006) exclude (** kwargs) Entry. objects. filter (... headline _ startswith = 'wh '...). exclude (... pub_date _ gte = datetime. date. today ()...). filter (... pub_date _ gte = datetime (2005, 1, 30 )... ) Return get () If you want to return the specified data one_enty = Entry. objects. get (pk = 1)
Field Query
_ Id
The specified query field name must correspond to the model field name unless the foreign key is used. objects. filter (blog_id = 4) at this time, the returned data is not the data row with id = 4 in the Entry, but the data row with the id corresponding to the primary key.
_ Exact
The most common case (Added by default) Entry. objects. get (headline _ exact = "Man bites dog") translated into SQL is SELECT... WHERE headline = 'man bites dog'; Blog. objects. get (id _ exact = 14) # clear form Blog. objects. get (id = 14) # _ exact added by default
_ Iexact
Blog. objects. get (name _ iexact = "beatles blog") may result in "Beatles Blog", "beatles blog", or "BeAtlES blOG". Case Insensitive
_ Contains
Entry. objects. get (headline _ contains = 'lennon') fuzzy search, translated into sqlSELECT... WHERE headline LIKE '% Lennon % ';
_ Icontains
Entry.objects.get(headline__icontains=’Lennon’)sql:SELECT ... WHERE headline ILIKE ’%Lennon%’;
_ In
Entry. objects. filter (id _ in = [1, 3, 4] SQL: SELECT... WHERE id IN (, 4); this can also be expressed IN the form of composite SQL inner_qs = Blog. objects. filter (name _ contains = 'didar ') entries = Entry. objects. filter (blog _ in = inner_qs) SQL: SELECT... WHERE blog. id IN (SELECT id FROM... where name like '% Cheddar % ')
_ Gt greater
Entry. objects. filter (id _ gt = 4) SQL: SELECT... WHERE id> 4 _ gte greater than or equal to _ lt less than _ lte less than or equal
_ Range
import datetimestart_date = datetime.date(2005, 1, 1)end_date = datetime.date(2005, 3, 31)Entry.objects.filter(pub_date__range=(start_date, end_date))sql:SELECT ... WHERE pub_date BETWEEN ’2005-01-01’ and ’2005-03-31’;
_ Year
Entry.objects.filter(pub_date_year=2005)sql:SELECT … WHERE pub_date BETWEEN ‘2005-01-01’ and ‘2005-12-31’;
_ Month _ day _ hour _ minute
Entry.objects.filter(pub_date__month=12)sql:SELECT ... WHERE EXTRACT(’month’ FROM pub_date) = ’12’;
_ Isnull
Entry.objects.filter(pub_date__isnull=True)sql:SELECT ... WHERE pub_date IS NULL;