python-django -orm frame correlation continues & ORM CRUD operations _20191110

python-django framework related -orm continue

 

orm is not commonly used fields:

1, BigIntegerField (IntegerField): phone number can be stored, using a string stored phone numbers,

- long integer (signed) -9223372036854775808 - 9223372036854775807

2, (Field,) BooleanField
- Boolean type

3,DateTimeField(DateField)

- date + time format YYYY-MM-DD HH: MM [: ss [.uuuuuu]] [TZ]

4, the time interval

DurationField (Field,)
- long integer interval stored in the database in accordance with bigint, is acquired in the ORM type datetime.timedelta

datetime Import
now datetime.datetime.now = ()
# Scene: picking up a seven-day coupon, seeking deadline is how much? ? ?
# This time used the interval ,, d
= datetime.timedelta (Days = 7)
Print (now + d)
Print (now)

----------------------------------------

5, now orm provided CharField, are verchar, if we wanted to change the type of char, orm is not supported, you need to define,

You can customize your own class, char fixed length of this interview, they might ask,  

 

###############################################

Field parameters

1,primary_key=True

2,max_length=32

3, to = 'table'

4,null=False

5,unique=True

6, default = 'Default'

7, db_index = True, if db_index = True represents the field to database indexes for this purpose. Index built much is not good, when the update will be slower,  

8, DatetimeField, DateField, TimeField this three time field, the following properties can be set

Configuring auto_now_add = True, create a data record when the current time will be added to the database.

Configuration auto_now = True, each time when updating the data record will update the field.

--------------------------------------------

Relationship field

ForeignKey

Foreign key is used to indicate the type of the foreign key relationship in the ORM, generally one of the fields provided ForeignKey 'many' in 'multiple' of.

to = 'table' to be associated with the setting table

to_field set the field to be associated,

on_delete, delete a table, the table how other related operations, if you delete a publishing house, is not following the book publishing house also deleted? ? ? This is not good, usually special treatment,

models.CASCADE
delete the associated data, delete the associated default is this, horrible,

models.DO_NOTHING
delete the associated data, causing errors IntegrityError

models.PROTECT
association delete data, causing errors ProtectedError

models.SET_NULL
delete the associated data, the value associated therewith is null (the precondition FK field should be set to be empty)

models.SET_DEFAULT
delete the associated data, associated with the value set to the default value (FK premise fields need to set the default value)

In the company, will not use the cascade operation, that is not a foreign key, foreign key of this and more, watch more, the relationship between the very complex, led to launch a body,

Full constraints established by the code, do not set foreign keys in the database level, when the sub-table is very sick,

db_constraint

Whether to create a foreign key constraint in the database, the default is True. If set to False, that is not associated,

 

----------------------------------

Meta information:

ORM corresponding class which contains Meta another class, and class encapsulates some Meta information database. The main fields are as follows:

db_table

ORM table name in the database app_ default is the class name, the name of the table can be rewritten by db_table.

index_together

Joint index.

unique_together

United unique index.

ordering

What specify the default sort field. This is the default when and in what sort of inquiry,

Meta - class:
Ordering = ( 'the create_time',) which is a tuple #

Only set this property, we query the results can be reverse ()

#########################################################################################

ORM CRUD operations,

1. Load django project

__name__ == IF '__main__':
os.environ.setdefault ( "DJANGO_SETTINGS_MODULE", "django_workspace.settings")
# This sentence is in manage.py environment inside,
Import Django
django.setup ()

from app01 import models

ret =models.Person.objects.all()
print(ret) 

2,    ret =models.Person.objects.all()

3,    ret=models.Person.objects.get(id=1)

4,       ret=models.Person.objects.filter(id=1)

  ret = models.Person.objects.filter (id__gt = 1) # id this formulation is greater than 1,

#filter if it is empty, does not complain, is an empty object, so the project must filter, almost do not get, avoid error! ! ! !

5,ret =models.Person.objects.exclude(id=1)

# This sentence is to exclude id = 1 off, then check out the other,

6, ret = models.Person.objects.all (). Values ​​() # which is out of all the fields, which is a sequence of dictionary,

    ret = models.Person.objects.all (). values ​​( 'name', 'create_time') # field may specify,

7, ret = models.Person.objects.all (). Values_list ( 'name', 'create_time') # This is the return of a tuple,

8,    ret =models.Person.objects.all().order_by('id')

9,    ret =models.Person.objects.all().order_by('id').reverse()

Note # reverse () only with defined generally on the order QuerySet that call (or call ordering specified ORDER_BY () method in class Meta model).

10,    ret =models.Person.objects.all().count()

11,    ret =models.Person.objects.all().first()

12,    ret =models.Person.objects.all().last()

13, ret = models.Person.objects.filter (id = 10) .exists () # if QuerySet contains data, returns True, otherwise False

This relatively tasteless, usually to check out the data to determine what, do not use this way,

-----------------------------------------------------

Single-table queries --- double underline operation,

1, ret = models.Person.objects.filter (id__gt = 1, id__lt = 3) # 1 is greater than the query, the data less than 3 ,,

2,ret =models.Person.objects.filter(id__in=[1,3]) #in操作,

3, ret = models.Person.objects.exclude (id__in = [1,3]) # 3 which is the negative data, not in

4, ret = models.Person.objects.filter (name__contains = 'xiao') # fuzzy query,

. 5, RET = models.Person.objects.filter (name__icontains = 'Xiao') #icontains this case insensitive, comprises a specified value,

6,ret =models.Person.objects.filter(id__range=[1,3]) #相当于between and

7, RET = models.Person.objects.filter (create_time__year = 2000) # This is a check of 2000,

--------------------------------------------------------------------------------

ForeignKey operation

Cross-table queries foreign keys,

First, check what is positive and what is a reverse investigation,

Where foreign key tables, is a positive check, otherwise reverse investigation,

# Forward queries
# `object lookup (cross table)
book_obj = models.Book.objects.all (). First ()
RET = book_obj.publisher
Print (RET)
RET = book_obj.publisher.name
Print (RET)
# lookup field (cross table)
# double underlined across the table,
RET = models.Book.objects.filter (the above mentioned id = 3) .values ( "publisher__name")

# 反向查询
publisher_obj=models.Publisher.objects.first()
ret =publisher_obj.book_set.all()

# Find a double underline,
RET = models.Publisher.objects.filter (the above mentioned id = 1) .values ( "books__title")
Print (RET)

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/andy0816/p/11832810.html