Django model select的各种用法详解
请跳转:
https://ops-coffee.cn/s/JVh4UnS2Tql9gUVaBSoGuA
补充:
class Student(models.Model):
name = models.CharField(max_length=10)
age = models.IntegerField()
class Score(models.Model):
studentId = models.ForeignKey(Student)
subject = models.CharField(max_length=10)
score = models.IntegerField()
创建:
方法一:
d = {
"name": "he",
"age" : 17,
}
rec = models.Student.objects.create(**d)
print("rec:%s"%rec) #rec:Student object
方法二:
rec = models.Student.objects.create(
name="miche",
age=16
)
方法三(支持回滚):
obj = models.Student()
obj.name = 'koko'
obj.age = 18
obj.save()
外键:
# 用一查多,小写
obj_02 = models.Student.objects.filter(id=1)[0]
subjects = obj_02.score_set.all()
# 用多查一
subjects = models.Score.objects.filter(studentId=1)[0]
cc=subjects.studentId.name
get 与filter 区别:
get不能修改(update),找不到会报错,
filter 可以修改,找不到不会报错