Django的ORM查询(学生成绩查询)

db_column 和 to_field共用

from django.db import models

# Create your models here.

class Student(models.Model):
    class Mate:
        db_table = 'students'

    student_id = models.AutoField(primary_key=True)
    name = models.CharField(unique=True, max_length=30, verbose_name='姓名')
    age = models.PositiveSmallIntegerField(verbose_name='年龄')

    def __repr__(self):
        return '{} {}'.format(self.name, self.age)

    __str__ = __repr__

class Score(models.Model):
    class Mate:
        db_table = 'scroes'

    score_id = models.AutoField(primary_key=True)
    subject = models.CharField(max_length=40, verbose_name='科目')
    score = models.PositiveSmallIntegerField(verbose_name='分数')
    name = models.ForeignKey(Student, db_column='name', to_field='name', on_delete=models.CASCADE)

    def __repr__(self):
        return '{} {} {}'.format(self.subject, self.score, self.name)

    __str__ = __repr__

 

插入数据

stu1 = Student(1, '王一涵', 10)
sco1 = Score(1, '语文', 90, '王一涵')
stu1.save()
sco1.save()

 

上一篇:Flutter扫码识别二维码内容


下一篇:django-关系映射 一对一 一对多 多对多