1、 一對多
model.py
class UserTest(models.Model):
name = models.CharField(max_length = 16 )
sex = models.CharField(max_length = 16 )
hobby = models.CharField(max_length = 32 )
class Ariticle(models.Model):
title = models.CharField(max_length = 32 )
content = models.CharField(max_length = 255 )
time = models.CharField(max_length=32)
admin_user2 = models.ForeignKey( to= UserTest ,on_delete=models.CASCADE)
view.py
def index(request):
p2 = UserTest.objects.create(name='小明同學', sex='男', hobby='籃球')
p1 = Ariticle(admin_user2=p2,title='八戒你瘦d了', content='不做大哥好多年', time='2018-1-8')
p1.save()
return HttpResponse(u"八戒你瘦了!")
2、一對一
一對一的情況和這個差不多,只要把外鍵的設置改成model.OneToOneField、多對多也是一樣的。
3、連表查詢
# 外鍵連表查詢,在添加外鍵的表上查用戶表 # p = Ariticle.objects.filter(title='八戒')[0] # 返回值是一個列表里面放對象 # print(p.admin_user2.name)

