Python Django loop inserted into mongodb database

Empire my love 2022-05-14 14:54:09 阅读数:1,001

pythondjangoloopinsertedmongodb

  Single to single table Association :

Start by inserting data into the loop MongoDB in , Then put the watch 1 Of ID Put it on the table 2 in , Then you can use the table 2 To see the table 1 了

import random
import pymongo
'''DBRef Associated table '''
from bson.dbref import DBRef
from django.http import HttpResponse
from bson.objectid import ObjectId
def Circular_Insertion(request):
# link mongo
client = pymongo.MongoClient("127.0.0.1:27017")
# mongo Database name
db = client.Chen
cursor1 = db.zhan1.find({})
cursor2 = db.zhan2.find({})
''' Insert the loop into the table of the database '''
# surname
first_name = [" Zhao ", " money ", " Grandchildren ", " Li ", " Zhou ", " Wu ", " zheng ", " king ", " feng ", " Chen ", " chu ", " Wei ", " a surname ", " Shen ", " Han ", " Yang ", " zhu ", " The qin dynasty ", " especially ", " xu ",
" What ", " Lu ", " Shi ", " Zhang "]
# Number of circular inserts
for i in range(3):
first=random.sample(first_name,1)
# name Random 10000 characters
last_names = chr(random.randint(0x4e00, 0x9fbf))
name=first[0]+last_names
# achievement
score1 = random.randint(0, 100)
score2 = random.randint(0, 100)
score3 = random.randint(0, 100)
# Inserted into the database zhan1 In the table
db.zhan1.insert_many([{'names': name, 'Subject': {"score1":score1,"score2":score2,"score3":score3,}}])
# Traverse zhan1 surface
for cur in cursor1:
# Traverse zhan1 In the table "_id"
str1 = (cur["_id"])
# Print zhan1 surface
print(cur)
# Number of circular inserts
for i in range(3):
# Telephone
phone=('13' + str(random.randrange(4, 10)) + ''.join(str(random.choice(range(10))) for _ in range(8)))
# class
grade = random.randint(1, 3)
# Age
age = random.randint(1, 100)
# Inserted into the database zhan2 Table of
db.zhan2.insert_many([{'ref':DBRef(collection="zhan1",id=str1),'grades': grade,'ages': age,'phones': phone}])
break
print('-'*200)
# adopt zhan2 Print zhan1 Information about
for j in cursor2:
show = db[j['ref'].collection].find({"_id": ObjectId(j['ref'].id)})
for pt in show:
print(pt)
break
print(j)
return HttpResponse(" Data insertion successful !")

  Printed data :

stay mongo Of cmd Data printed in : 

版权声明:本文为[Empire my love]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141446235470.html