Question.objects.all() # 等价于 # select question_text from polls_question;
按字段查询
pk意为PRIMARY KEY,等价于当前模型中的 id
1 2 3 4 5
Question.objects.filter(id=1) | Question.objects.filter(pk=1) Question.objects.filter(question_text="What's new?") # 等价于 select question_text from polls_question where id=1; select question_text from polls_question where question_text="What's new?";
模糊查找
1 2 3
Question.objects.filter(question_text__startswith='What') # 等价于 select question_text from polls_question where question_text like'how%';
q = Question.objects.get(pk=1) q.choice_set.create(choice_text='Not much', votes=0) # 等价于 insert into polls_choice (id,choice_text,votes,question_id) value ('1','Not much','0','1');
查找记录数量
1 2 3
q.choice_set.count() # 等价于 selectcount(*) from polls_choice as c join polls_question as q on c.question_id=q.id where q.id='1' ;
连接查询
通过从表对象按主表条件查询
1 2 3
Choice.objects.filter(question__pub_date__year=current_year) # 等价于 select choice_text from polls_choice as c join polls_question as q on c.question_id=q.id whereyear(q.pub_date) =(selectyear(curdate()));
模糊查询并删除记录
1 2 3
q.choice_set.filter(choice_text__startswith='Just hacking').delete() # 等价于 deletefrom polls_choice where choice_text like'Just hacking%';