Django视图之ORM连表操作一

时间:2022-01-17 06:11:48

1 项目路径结构树

 Django视图之ORM连表操作一

 

2 models创建类

 

from django.db import models

class UserType(models.Model):

'''

用户类型

'''

title = models.CharField(max_length=12)


class UserInfo(models.Model):

'''

用户表

'''

name = models.CharField(max_length=16)

age = models.IntegerField()

 ut = models.ForeignKey('UserType')

  

CharField :char类型

IntegerField: int类型

ForeignKey: 关联表

 

3 检测app是否注册项目

 Django视图之ORM连表操作一

 

添加app01

Django视图之ORM连表操作一

 

 

4 初始化数据库

初始化db.sqlite3数据库

1.创建表结构

>>python manage.py makemigrations

Migrations for 'app01':

app01\migrations\0001_initial.py

- Create model UserInfo

- Create model UserType

- Add field ut to userinfo

  

2. 初始化数据库

>> python manage.py migrate

Operations to perform:

Apply all migrations: admin, app01, auth, contenttypes, sessions

Running migrations:

Applying contenttypes.0001_initial... OK

Applying auth.0001_initial... OK

Applying admin.0001_initial... OK

Applying admin.0002_logentry_remove_auto_add... OK

Applying app01.0001_initial... OK

Applying contenttypes.0002_remove_content_type_name... OK

Applying auth.0002_alter_permission_name_max_length... OK

Applying auth.0003_alter_user_email_max_length... OK

Applying auth.0004_alter_user_username_opts... OK

Applying auth.0005_alter_user_last_login_null... OK

Applying auth.0006_require_contenttypes_0002... OK

Applying auth.0007_alter_validators_add_error_messages... OK

Applying auth.0008_alter_user_username_max_length... OK

Applying sessions.0001_initial... OK

  

5 创建表数据

1)     urls映射关系

urlpatterns = [

url(r'^create_data/', views.create_data),

]

  

2)     创建视图函数

from django.shortcuts import render,redirect,HttpResponse

from app01 import models



# Create your views here.



def create_data(request):

'''创建书籍'''

#models.UserType.objects.create(title='普通用户')

#models.UserType.objects.create(title='白金用户')

#models.UserType.objects.create(title='砖石用户')

'''创建用户'''

  #models.UserInfo.objects.create(name='alex',age=32,ut_id=1)

#models.UserInfo.objects.create(name='egon',age=42,ut_id=2)

#models.UserInfo.objects.create(name='yuan',age=32,ut_id=3)

#models.UserInfo.objects.create(name='naza',age=32,ut_id=1)



'''获取数据'''

result = models.UserInfo.objects.all()

for obj in result:

print(obj.name,obj.age)

 

    return HttpResponse('...')

  

 

'''

alex 32

egon 42

yuan 32

naza 32



'''

  

 

 

 

 

跨表操作获取数据

result = models.UserInfo.objects.all()

for obj in result:

print(obj.name,obj.age,obj.ut.title)



alex 32 普通用户

egon 42 白金用户

yuan 32 砖石用户

naza 32 普通用户

  

6 访问初始化数据

http://127.0.0.1:8000/create_data/