Django model layer operation and ORM

Single-table queries

queryset object can be unlimited point method queryset

New data

Based Queryset

models.对应表的类名.objects.create(字段名 = 值,……)

Object-based

object = models.对应表的类名(字段名 = 值,……)

object.save()

change the data

Based Queryset

models.对应表的类名.objects.filter(字段名 = 值[查找条件]).update(字段名=值[更改后的数据])

Object-based

object = models.对应表的类名.objects.filter(字段名 = 值[查找条件]).first()

object.字段名 = 值

object.save()

delete data

Based Queryset

models.对应表的类名.objects.filter(字段名 = 值[查找条件]).delete()

Object-based

object = models.对应表的类名.objects.filter(字段名 = 值[查找条件]).first()

object.delete()

Query data

1. all(): Search results

2 filter(**kwargs): It contains the objects to match the filter, the filter can be put in a plurality of constraints, and the relationship between a plurality of conditions

3 get(**kwargs): Returns the filter criteria to match the result is returned and only one, if the object matching the filter will throw more than one or no errors.

4 exclude(**kwargs): It contains the filter conditions given object does not match

5 order_by(*field): sort query results, the default values in parentheses are in ascending order, a negative sign in front of the value - is descending

6 reverse(): Reverse sort query results, the previous first have to reverse sort

7 count(): Returns the database that match the query (QuerySet) the number of objects

8 first(): return the first record

9 last(): Returns the last record

10 exists(): If QuerySet contains data, returns True, otherwise False

11 values(*field): Returns a ValueQuerySet-- QuerySet that a special, not obtained after running a series of instantiating an object model, but an iterative sequence dictionaries

12 values_list(*field): it values () are very similar, it returns a sequence of tuples (listing sets tuples), return values is a sequence of dictionary

13 distinct(): From the returned results to eliminate duplicate records heavy object must be exactly the same data in order to weight (for example, if id different but all other things being equal record will not be deleted, but let's assign the same field, and then for this removes the same data)

Double-crossed inquiry

Syntax: __ query field name = value

1 .__ gt = value: greater than the ......

2 .__ gte = value: greater than or equal to ......

3 .__ lt = value: less than the ......

4 .__ lte = value: less than or equal to ......

5 .__ in = [value 1, value 2, ......]: in the list of values

6 .__ range = [x, y]: x and y is in the range

7 .__ year = value: Year

8 .__ contains = value: ...... comprising (case sensitive)

9 .__ icontains = Value: ...... comprising (case insensitive)

10 .__ startswith = value: the beginning ......

11 .__ endswith = value: at the beginning ......

Multi-table query

chestnut:

Database Design

Book table book: id, title, price, publish_date

On the table author: id, name, age

Press Table publish: id, name, addr, email

Details of the table: id, phone, addr

Relationships between tables

Book and Author tables is many to many relationship

Book publishers table and the table is many- relationship

Details of the table and the author table is one to one relationship

Model table

class Book(models.Model):
    # 主键不指定默认创建id字段为主键
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8,decimal_places=2)
    publish_date = models.DateField(auto_now_add=True)  # auto_now:每次操作改数据都会自动更新时间,auto_now_add:新增数据的时候会将当前时间自动添加,后续的修改该字段不会自动更新
    # 外键关系
    publish = models.ForeignKey(to='Publish')
    authors = models.ManyToManyField(to='Author')  # 虚拟字段, 信号字段

    def __str__(self):
        return '书籍对象的名字:%s'%self.title


class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)
    email = models.EmailField()  # 对应就是varchar类型

    def __str__(self):
        return '出版社对象的名字:%s'%self.name


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    authordetail = models.OneToOneField(to='AuthorDetail')

    def __str__(self):
        return  '作者对象的名字:%s'%self.name


class AuthorDetail(models.Model):
    phone = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)

Field assignment as foreign key relationships

1. Direct Write Data: publish_id = 1

models.Book.objects.create(title='红楼梦',price=66.66,publish_id=1)

2. The transfer of data objects: publish = publish_obj

publish_obj = models.Publish.objects.filter(pk=2).first()
models.Book.objects.create(title='三国演义',price=199.99,publish=publish_obj)

Add the relationship between the table and the table

add: support for digital transmission or an object, and can pass more

表1_object = models.对应表1的类名.objects.filter(字段名 = 值[查找条件]).first()

表1_object.与表2的关联字段.add(数字或表2对象)

Modify the relationship between the table and the table

set: pass must be iterative object (with the ancestral form)

表1_object = models.对应表1的类名.objects.filter(字段名 = 值[查找条件]).first()

表1_object.与表2的关联字段.set((数字,)或表2对象)

Delete relationships between tables and tables

remove: queryset needs to be broken up,*<queryset>

表1_object = models.对应表1的类名.objects.filter(字段名 = 值[查找条件]).first()

表1_object.与表2的关联字段.remove((数字,)或打散的表2对象)

The relationship between the table and the table cleared

clear (): Empty your current relationship is binding table corresponding to the record

表1_object = models.对应表1的类名.objects.filter(字段名 = 值[查找条件]).first()

表1_object.与表2的关联字段.clear()

Based on the query object table

Forward and reverse lookup queries : query by field forward, reverse lookup by table name in lowercase

Forward and reverse lookup queries judgment is based on whether the associated field in the table

Forward

表1_object = models.对应表1的类名.objects.filter(字段名 = 值[查找条件]).first()

表1_object.与表2的关联字段[.all()].表2字段

Reverse

表2_object = models.对应表2的类名.objects.filter(字段名 = 值[查找条件]).first()

表2_object.与表1名小写_set[.all()].表1字段

Many-to-many relationship and the relationship between If not .all()displayed 项目名.对应表的类名.None, since the corresponding relationship check out the results of more than one, and one relationship, do not require.

Query-based dual-line decline

Forward

models.对应表1的类名.objects.filter(字段名 = 值[查找条件]).value(与表2关系字段__查询的字段名)

Reverse

models.对应表2的类名.objects.filter(字段名 = 值[查找条件]).value(对应表1的类名小写__查询的字段名)

Aggregate query aggregate

Introducing a polymerizable functionfrom django.db.models import Max,Min,Count,Sum,Avg

models.对应表的类名.objects.filter(字段名 = 值[查找条件]).aggregate(别名=聚合函数(字段名[双下划线查询适用]))

Grouping queries annotate

models.对应表的类名.objects.annotate(别名=聚合函数(字段名[双下划线查询适用])).values(分组字段,别名)

Guess you like

Origin blog.csdn.net/weixin_43860025/article/details/91629627