Django- ORM连表操作

ORM增删改查

# 数据库相关操作
def index1(req):
    from app01 import models
    # 增加
    # models.UserGroup.objects.create(title='产品')
    models.UserInfo.objects.create(user='root',password='pwd',age=12,ug_id=1)

    # 查找
    # group_list = models.UserGroup.objects.all()
    # group_list = models.UserGroup.objects.filter(id=1,title='销售')
    # group_list = models.UserGroup.objects.filter(id__gt=1)
    # print(group_list)


    # 删除
    models.UserGroup.objects.filter(id=2).delete()
    models.UserGroup.objects.filter(id=3).update(title='公关部')


    group_list = models.UserGroup.objects.all()
    user_list = models.UserInfo.objects.all()

    # for row in user_list:
    #     print(row.user, row.password, row.ug_id, row.ug.title, row.ug.fo.caption)

    obj = models.UserInfo.objects.all().first()

    gp1 = models.UserGroup.objects.first()
    
    # 反向查找 userinfo_set
	a = gp1.userinfo_set.all()
    print(a)


    print('first',obj.user, obj.password)




    return render(req, 'index1.html',{'group_list':group_list})

表结构

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    """
    员工
    """
    nid = models.BigAutoField(primary_key=True)
    user = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField(default=0)
    ug = models.ForeignKey('UserGroup',null=True,on_delete=models.CASCADE)




class UserGroup(models.Model):
    """
    部门
    """
    title = models.CharField(max_length=32)
    fo = models.ForeignKey('Foo',on_delete=models.CASCADE,null=True)

class Foo(models.Model):

    caption = models.CharField(max_length=16)

你可能感兴趣的:(Django,python,django)