Django-ORM database operations and multi-table query

In the ORM framework, which help us to classes and data tables a map, it allows us to corresponding data in the table will be able to operate through classes and objects.

django ORM framework embedded in, you need not be directly oriented database programming, but the class definition model, completion of additions and deletions by the data table class and object model change search operation.

Create a data table object
  • Create two model class
    books and class hero class, a book has more than a hero.
from django.db import models

#定义图书模型类BookInfo
class BookInfo(models.Model):
    btitle = models.CharField(max_length=20, verbose_name='名称')
    bpub_date = models.DateField(verbose_name='发布日期')
    bread = models.IntegerField(default=0, verbose_name='阅读量')
    bcomment = models.IntegerField(default=0, verbose_name='评论量')
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_books'  # 指明数据库表名
        verbose_name = '图书'  # 在admin站点中显示的名称
        verbose_name_plural = verbose_name  # 显示的复数名称

    def __str__(self):
        """定义每个数据对象的显示信息"""
        return self.btitle

#定义英雄模型类HeroInfo
class HeroInfo(models.Model):
    GENDER_CHOICES = (
        (0, 'female'),
        (1, 'male')
    )
    hname = models.CharField(max_length=20, verbose_name='名称') 
    hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='性别')  
    hcomment = models.CharField(max_length=200, null=True, verbose_name='描述信息') 
    hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='图书')  # 外键
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_heros'
        verbose_name = '英雄'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.hname
  • Auto-increment primary keys idwithout a separate set automatically created.
  • ForeignKeyA foreign key is set in the hero category, which is more than many relationship belong to that party.
  • ForeignKeyWhen the field is bound is not specified, the default binding primary key id.
Add, delete, change,
  • 增:save、create
  1. Direct methods preservation by creating a model class object, perform save () to the database.
>>> from datetime import date
>>> book = BookInfo(
    btitle='西游记',
    bput_date=date(1988,1,1),
    bread=10,
    bcomment=10
)
>>> book.save()
  1. Save by model class .objects.create ().
>>> HeroInfo.objects.create(
    hname='沙悟净',
    hgender=0,
    hbook=book
)
<HeroInfo: 沙悟净>
  • 删: delete
  1. Object-.delete get acquired ()
hero = HeroInfo.objects.get(id=13)
hero.delete()
  1. .Delete filter obtained using object ()
HeroInfo.objects.filter(id=14).delete()
  • 改:save、update
  1. And save the re-assignment model class object properties
hero = HeroInfo.objects.get(hname='猪八戒')
hero.hname = '猪悟能'
hero.save()
  1. Update object properties model class, returns the number of rows affected
HeroInfo.objects.filter(hname='沙悟净').update(hname='沙僧')
  • Search
    queries are used most often is the use of relatively more complicated, especially when it comes to multi-table queries have foreign keys.
    1. Single table underlying query: get, all

    • GET
      GET query if no tie to the data throws an exception.
    >>> book = BookInfo.objects.get(btitle='西游记')
    >>> book.id
    
    • all
      return all results objects
      >>> BookInfo.objects.all()
    
    • first
      returns the first result object qualified.

    2. Filter query
    list only use the filter.

    • It is equal to: exact (can be omitted)
    BookInfo.objects.filter(id__exact=1)
    # 可简写为:
    BookInfo.objects.filter(id=1)
    
    • Contains: contains
      query Title contains 'pass' books.
    BookInfo.objects.filter(btitle__contains='传')
    
    • Empty query: isnull
      query Title is not empty of books.
    BookInfo.objects.filter(btitle__isnull=False)
    
    • Compare query:
      syntax is similar, no longer listed
      • gt greater than
      • greater than or equal gte
      • lt is less than
      • less lte

    The remaining some filter query inquiry is also very simple, not recorded.

3. functions polymerization
aggregation function comprising: Avg average, Count number, Max Max, Min Min, Sum summation, is defined in django.db.models.

count query the total number of books:

BookInfo.objects.count()

order_by Sort:

BookInfo.objects.all().order_by('bread')  # 升序
BookInfo.objects.all().order_by('-bread')  # 降序
4. Related Queries

The most important and most confusing part is associated with the query.

  • One to several (note whether a foreign key attribute the related_name)
    (table does not contain the foreign key to the table query containing the foreign key)
    一对应的模型类对象.多对应的模型类名小写_set
b = BookInfo.objects.get(id=1)
b.heroinfo_set.all()

If the foreign key is defined ralated_nameattributes,
such as when the foreign key is defined as follows:

hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='图书', ralated_name = "book")  # 外键

Multi-query statement to the moment:

b = BookInfo.objects.get(id=1)
b.book.all()

Using a defined ralated_namename substitution 模型类名小写_set, such wording should be simple and more convenient.

  • Many to one
    (query from a table containing the foreign key table to the foreign key mapping)
    多对应的模型类对象.多对应的模型类中的关系类属性名
h = HeroInfo.objects.get(id=1)
h.hbook
  • Access to a model class associated with the corresponding object id:
    (a query from a table containing the foreign key table to the foreign key id attribute mapping)
    多对应的模型类对象.关联类属性_id
h = HeroInfo.objects.get(id=1)
h.hbook_id

The associated filter query

Query method:关联模型类名小写__属性名__条件运算符=值

Example:

# 查询图书,要求图书英雄为"孙悟空"
BookInfo.objects.filter(heroinfo__hname='孙悟空')
# 查询图书,要求图书中英雄的描述包含"八"
BookInfo.objects.filter(heroinfo__hcomment__contains='八')
# 查询英雄, 要求所属书名为"天龙八部"
HeroInfo.objects.filter(hbook__btitle='天龙八部')
# 查询英雄,要求所属图书阅读量大于30
HeroInfo.objects.filter(hbook__bread__gt=30)

Usage is understood, what is ultimately a query, then it EDITORIAL its associated table to indicate in lowercase query, filter conditions connected by a double underline.

Guess you like

Origin blog.csdn.net/weixin_34204057/article/details/90786462