问题:假设已有一个数据库,现要用Django项目,对该数据库进行连接,进行ORM操作
条件:
1. 数据库(PGsql):
- database:industrial_map_db
- table: industrial_map.company
就两条数据,意思意思~
2. Django项目
- 想把刚刚的表映射到该项目的models中,并采用相同的数据库进行ORM操作
1.先连接数据库
两个项目如果连接相同的数据库,该数据是可以共享的,但前提是有相应的models
比如B项目的表本无数据,连接后,操作数据试一试:
C:\Users\Administrator\Desktop\华社测试\rqapiv2>python manage.py shell
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from aqcapi.models import Base
>>> Base.objects.all()
<QuerySet [<Base: 1>, <Base: 2>, <Base: 3>, <Base: 4>, <Base: 5>, <Base: 6>, <Base: 7>, <Base: 8>, <Base: 9>, <Base: 10>, <Base: 108>, <Base: 109>, <Base: 1168>, <Base: 11>, <Base: 12>, <Base:
13>, <Base: 14>, <Base: 15>, <Base: 16>, <Base: 17>, '...(remaining elements truncated)...']>
2.反向生成models
python manage.py inspectdb
这个操作是将整个A项目的表移植过来了python manage.py inspectdb > APP名/models.py
指定生成APP名下面的models.py
C:\Users\Administrator\Desktop\华社测试\rqapiv2>python manage.py inspectdb
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
class AuthGroup(models.Model):
name = models.CharField(unique=True, max_length=150)
class Meta:
managed = False
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
id = models.BigAutoField(primary_key=True)
group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'auth_group_permissions'
unique_together = (('group', 'permission'),)
class AuthPermission(models.Model):
name = models.CharField(max_length=255)
content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING)
codename = models.CharField(max_length=100)
class Meta:
managed = False
db_table = 'auth_permission'
unique_together = (('content_type', 'codename'),)
class AuthUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.BooleanField()
username = models.CharField(unique=True, max_length=150)
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
email = models.CharField(max_length=254)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
managed = False
db_table = 'auth_user'
class AuthUserGroups(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'auth_user_groups'
unique_together = (('user', 'group'),)
class AuthUserUserPermissions(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'auth_user_user_permissions'
unique_together = (('user', 'permission'),)
class Company(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
age = models.IntegerField()
address = models.CharField(max_length=25, blank=True, null=True)
salary = models.DecimalField(max_digits=18, decimal_places=2, blank=True, null=True)
class Meta:
managed = False
db_table = 'company'
class DjangoAdminLog(models.Model):
action_time = models.DateTimeField()
object_id = models.TextField(blank=True, null=True)
object_repr = models.CharField(max_length=200)
action_flag = models.SmallIntegerField()
change_message = models.TextField()
content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING, blank=True, null=True)
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'django_admin_log'
class DjangoApschedulerDjangojob(models.Model):
id = models.CharField(primary_key=True, max_length=255)
next_run_time = models.DateTimeField(blank=True, null=True)
job_state = models.BinaryField()
class Meta:
managed = False
db_table = 'django_apscheduler_djangojob'
class DjangoApschedulerDjangojobexecution(models.Model):
id = models.BigAutoField(primary_key=True)
status = models.CharField(max_length=50)
run_time = models.DateTimeField()
duration = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
finished = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
exception = models.CharField(max_length=1000, blank=True, null=True)
traceback = models.TextField(blank=True, null=True)
job = models.ForeignKey(DjangoApschedulerDjangojob, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'django_apscheduler_djangojobexecution'
class DjangoContentType(models.Model):
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
managed = False
db_table = 'django_content_type'
unique_together = (('app_label', 'model'),)
class DjangoMigrations(models.Model):
id = models.BigAutoField(primary_key=True)
app = models.CharField(max_length=255)
name = models.CharField(max_length=255)
applied = models.DateTimeField()
class Meta:
managed = False
db_table = 'django_migrations'
class DjangoSession(models.Model):
session_key = models.CharField(primary_key=True, max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'django_session'
class EoiasCompanyBaseInfoExtend(models.Model):
id = models.BigAutoField(primary_key=True)
company_name = models.TextField()
company_name_alias = models.TextField(blank=True, null=True)
legal_person = models.TextField(blank=True, null=True)
province = models.TextField(blank=True, null=True)
city = models.TextField(blank=True, null=True)
county = models.TextField(blank=True, null=True)
website_url = models.TextField(blank=True, null=True)
phone_number = models.TextField(blank=True, null=True)
email = models.TextField(blank=True, null=True)
end_date = models.TextField(blank=True, null=True)
ent_type = models.TextField(blank=True, null=True)
status = models.TextField(blank=True, null=True)
industries = models.TextField(blank=True, null=True)
regist_capital = models.TextField(blank=True, null=True)
paid_capital = models.TextField(blank=True, null=True)
insured_persons_number = models.TextField(blank=True, null=True)
staff_number = models.TextField(blank=True, null=True)
credit_code = models.TextField(blank=True, null=True)
taxpayer_identification_number = models.TextField(blank=True, null=True)
registration_number = models.TextField(blank=True, null=True)
import_and_export_enterprise_code = models.TextField(blank=True, null=True)
org_code = models.TextField(blank=True, null=True)
check_date = models.DateTimeField(blank=True, null=True)
term_start_end = models.TextField(blank=True, null=True)
addr = models.TextField(blank=True, null=True)
company_kind = models.TextField(blank=True, null=True)
company_en_name = models.TextField(blank=True, null=True)
company_origin_name = models.TextField(blank=True, null=True)
start_date = models.DateTimeField(blank=True, null=True)
belong_org = models.TextField(blank=True, null=True)
scope = models.TextField(blank=True, null=True)
company_profile = models.TextField(blank=True, null=True)
is_on_stock = models.TextField(blank=True, null=True)
listed_status = models.TextField(blank=True, null=True)
stock_number = models.TextField(blank=True, null=True)
company_label = models.TextField(blank=True, null=True)
taxpayers_type = models.TextField(blank=True, null=True)
data_update_time = models.TextField(blank=True, null=True)
logo = models.TextField(blank=True, null=True)
update_time = models.DateTimeField()
created_time = models.DateTimeField()
class Meta:
managed = False
db_table = 'eoias_company_base_info_extend'
class Info(models.Model):
id = models.BigAutoField(primary_key=True)
company_name = models.CharField(unique=True, max_length=100)
date_base = models.DateTimeField(blank=True, null=True)
date_leads = models.DateTimeField(blank=True, null=True)
date_share_holder = models.DateTimeField(blank=True, null=True)
date_sub_company = models.DateTimeField(blank=True, null=True)
date_change = models.DateTimeField(blank=True, null=True)
date_finance = models.DateTimeField(blank=True, null=True)
date_tender = models.DateTimeField(blank=True, null=True)
date_investment = models.DateTimeField(blank=True, null=True)
date_copyright = models.DateTimeField(blank=True, null=True)
date_software_copyright = models.DateTimeField(blank=True, null=True)
date_certification = models.DateTimeField(blank=True, null=True)
date_website = models.DateTimeField(blank=True, null=True)
date_patents = models.DateTimeField(blank=True, null=True)
date_customer = models.DateTimeField(blank=True, null=True)
date_supplier = models.DateTimeField(blank=True, null=True)
date_annual_report = models.DateTimeField(blank=True, null=True)
date_brand = models.DateTimeField(blank=True, null=True)
update_time = models.DateTimeField()
created_time = models.DateTimeField()
class Meta:
managed = False
db_table = 'info'
我们把company表的models指令找出来,粘到B项目的文件中:
class Company(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
age = models.IntegerField()
address = models.CharField(max_length=25, blank=True, null=True)
salary = models.DecimalField(max_digits=18, decimal_places=2, blank=True, null=True)
class Meta:
managed = False
db_table = 'company'
==============================================================
# 加上别名
class Company(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(verbose_name='名称', max_length=20)
age = models.IntegerField(verbose_name='年龄')
address = models.CharField(verbose_name='地址', max_length=25, blank=True, null=True)
salary = models.DecimalField(verbose_name='薪资', max_digits=18, decimal_places=2, blank=True, null=True)
class Meta:
verbose_name = verbose_name_plural = '公司人员信息'
managed = False
db_table = 'company'
生产单表
python manage.py inspectdb --database default TableName
将指定的表生成对应的Modelpython manage.py inspectdb --database default district_info > zsdt/models.py
将指定的表生成对应的Model 导入到指定的models.py 文件
C:\Users\Administrator\Desktop\华社测试\rqapiv2>python manage.py inspectdb --database default company
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
class Company(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
age = models.IntegerField()
address = models.CharField(max_length=25, blank=True, null=True)
salary = models.DecimalField(max_digits=18, decimal_places=2, blank=True, null=True)
class Meta:
managed = False
db_table = 'company'
3.数据迁移
C:\Users\Administrator\Desktop\华社测试\rqapiv2>python manage.py makemigrations aqcapi
Migrations for 'aqcapi':
aqcapi\migrations\0002_company.py
- Create model Company
C:\Users\Administrator\Desktop\华社测试\rqapiv2>python manage.py migrate aqcapi
Operations to perform:
Apply all migrations: aqcapi
Running migrations:
Applying aqcapi.0002_company... OK
4.验证
C:\Users\Administrator\Desktop\华社测试\rqapiv2>python manage.py shell
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from aqcapi.models import Company
>>> Company.objects.values()
<QuerySet [{'id': 1, 'name': 'Paul', 'age': 32, 'address': 'California ', 'salary': Decimal('20000.00')}, {'id': 2, 'name': 'Tom', 'age': 29, 'address': 'Beijing
', 'salary': Decimal('32000.00')}]>
>>>
可以看到,数据已经可以操作了