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)