淦
Teacher为模板(model)
#查询全部
Teacher.objects.all()
#select...where 查询单个
Teacher.objects.get(no=selected_no)
#查询负责此课程的全部老师
Teacher.objects.filter(subject=subject)
#连接Subject查询,内联,外联好像自动的
Teacher.objects.all().only('name','intro','gcount','bcount','subject').select_related('subject')
#指定select 的内容
Teacher.objects.all().only('name','subject')
# value 和 annotate 相当于group by value
Teacher.objects.values('subject__name').annotate(good=Avg('good_count'), bad=Avg('bad_count')
注意:
--get 只有一条记录返回的时候才正常,也就说明get的查询字段必须是主键或者唯一约束的字段。当返回多条记录或者是没有找到记录的时候都会抛出异常
--filter 有没有匹配的记录都可以,没有的话就返回空
model如下:
class Subject(models.Model):
no = models.AutoField(primary_key=True,verbose_name='编号')
name = models.CharField(max_length=50,verbose_name='名称')
intro = models.CharField(max_length=1000,verbose_name='介绍')
is_hot = models.NullBooleanField(verbose_name='是否热门')
class Meta:
managed = False
db_table = 'tb_subject'
verbose_name = '学科'
verbose_name_plural = '学科'
def __str__(self):
return f'{self.name}'
class Teacher(models.Model):
no = models.AutoField(primary_key=True,verbose_name='编号')
name = models.CharField(max_length=20,verbose_name='名称')
sex = models.IntegerField(default=True,verbose_name='性别')
birth = models.DateField(verbose_name='出生日期')
intro = models.CharField(max_length=1000,verbose_name='个人介绍')
photo = models.CharField(max_length=255,verbose_name='照片')
gcount = models.IntegerField(default=0,db_column='gcount',verbose_name='好评数')
bcount = models.IntegerField(default=0,db_column='bcount',verbose_name='差评数')
subject = models.ForeignKey(Subject,null=True,on_delete=models.SET_NULL,db_column='sno')
class Meta:
managed = False
db_table = 'tb_teacher'
verbose_name = '老师'
verbose_name_plural = '老师'