FK关联
url.py里
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index.html$', views.index),
]
views.py里
from django.shortcuts import render,HttpResponse
from app01 import models
def index(request):
zgl = models.UserInfo.objects.filter(username='zgl',gender=1).first() # 拿到要查询的对象
result = zgl.girls.all() # 去U2U里拿到所有的b_id
for u in result:
print(u.g.nickname) # 拿到b_id所对应的.g的女孩的nickname
return HttpResponse('successfully done')
models.py里
from django.db import models
class UserInfo(models.Model):
nickname = models.CharField(max_length=16)
username = models.CharField(max_length=16)
passwd = models.CharField(max_length=64)
gender_choice = (
(1,'男'),
(2,'女'),
)
gender= models.IntegerField(choices=gender_choice)
# 反向查询时
# related_query_name
# obj对象男.U2U.girls_set.all()
# obj对象女.U2U.boys_set.all()
# related_name
# obj对象男.girls.all()
# obj对象女.boys.all()
class U2U(models.Model):
g = models.ForeignKey('UserInfo',related_name='boys')
b = models.ForeignKey('UserInfo',related_name='girls')
M2M自关联特性:
models.py里
from django.db import models
class UserInfo(models.Model):
nickname = models.CharField(max_length=16)
username = models.CharField(max_length=16)
passwd = models.CharField(max_length=64)
gender_choice = (
(1,'男'),
(2,'女'),
)
gender= models.IntegerField(choices=gender_choice)
m = models.ManyToManyField('UserInfo') # 自己关联自己
views.py里
def index(request):
#查女生
girl = models.UserInfo.objects.filter(id=4,gender=2).first() # 拿到要查询的对象
result = girl.userinfo_set.all()
for row in result:
print(row.nickname)
return HttpResponse('successfully done')
obj = models.UserInfo.objects.filter(id=1).first()
# 对于from_userinfo_id 相当于正向查询通过.m的方式
obj.m => select xx from xx where from_userinfo_id = 1
# 对于to_userinfo_id 相当于反向查询通过.userinfo_set的方式
obj.userinfo_set => select xx from xx where to_userinfo_id = 1
定义:
# 前面列:男生ID
# 后面列:女生ID
应用:
# 男生对象
obj = models.UserInfo.objects.filter(id=1).first()
# 根据男生ID=1查找关联的所有的女神
obj.m.all()
# 女生
obj = models.UserInfo.objects.filter(id=4).first()
# 根据女生ID=4查找关联的所有的男生
obj.userinfo_set.all()
问题:
当打不开页面,发生404错误时
url(r'^index.html$/', love.index) # index.html$后边不要加反斜杠