django foreignkey外键使用的例子 相当于left join
django外键使用一对一
因为django中处于安全和方便将数据库中的表封装成模型,所以很多sql原生的功能无法使用,比如leftjoin,但是我们可以使用外键(foreignkey)来满足表表直接的关系。
设置模型
#在models.py中添加 #Person模型有两个外键,School和Province # classProvince(models.Model): name=models.CharField('省份',max_length=10) post=models.CharField('邮编',max_length=10) def__str__(self):#在Python2中用__unicode__替换__str__ returnself.name #classSchool_Type(models.Model): #school_type=models.CharField('学校类别') classSchool(models.Model): id=models.IntegerField('学校编号',primary_key=True) name=models.CharField('学校名称',max_length=200) address=models.CharField('学校地址',max_length=200) def__str__(self):#在Python2中用__unicode__替换__str__ returnself.name classPerson(models.Model): name=models.CharField('姓名',max_length=50) age=models.IntegerField('年龄') address=models.CharField('地址',max_length=100) email=models.EmailField('电子邮件') school=models.ForeignKey(School,on_delete=models.CASCADE) province=models.ForeignKey(Province,on_delete=models.CASCADE)
设置ModelForm
因为Form的字段跟model的字段相同,所以我们直接使用ModelForm,使用ModelForm时外键会以ChoiceField字段来显示,显示为str()返回的字段
#因为Form的字段跟model的字段相同,所以我们直接使用ModelForm classPersonForm(ModelForm): classMeta: model=Person fields='__all__'
保存
views.py中的view,可以直接使用form.save()来保存form defperson(request): ifrequest.POST: form=PersonForm(request.POST) ifform.is_valid(): p=form.save() returnHttpResponse(request,'success') else: returnHttpResponse(request,'fail') else: form=PersonForm() person_list=Person.objects.all() #school_list=person_list.School_set.all() returnrender(request,'person.html',locals())
模版person.html
可以在模版中使用person.外键字段.外键表属性来显示数据,比如person.school.province.post
{%extends'base.html'%} {%blockcontent%}{%csrf_token%} {{form}} {##} {%forpersoninperson_list%} name:{{person.name}};age:{{person.age}};school:{{person.school}} {{person.province.post}}
{%endfor%} {#{{school_list}}#} {%endblock%}
以上这篇djangoforeignkey外键使用的例子相当于leftjoin就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。