我正在学习如何集成Python和MongoDB,所以我给自己设置了一个挑战:创建一个小程序来注册足球运动员。
我的程序有两个模块,info_player和info_team。我将以交互方式运行程序(python -i)。第一个模块接收有关玩家和第二个模块的信息,有关团队的信息,以及一些查询和保存在数据库中。
我设计了我的数据库如下,数据库被称为“锦标赛”,集合是“团队”,文档是“玩家”。换句话说,球队和球员之间存在一对多的关系。
我的问题:我是否需要将对象转换为Json(思考to_json
方法)?如何保存和查询?
info_player:
class Player:
def __init__(self, name, age, nationality="brazilian", team):
"""
initializating Jogador class
"""
self.personal(name, age, country)
self.professional(team)
def personal(self, name, age, nationality, dominancy, height):
"""
personal data about players
"""
self.name = name
self.age = age
self.nationality = nationality
self.height = height
self.dominancy = dominancy # righty, lefty or ambidextrous
def profissional(self, position, number, team, primary):
"""
professional data about players
"""
self.position = position
self.number = number
self.team = team
self.primary = False # is he a regular member of a team?
def to_Json():
pass
info_team:
from pymongo import MongoClient
from info_player import Player
class TeamDB:
def __init___(self, nome, fundacao, federacao):
self.name = name
self.foundationData = foundationData
self.federation = federation
def initializeDB():
client = MongoClient('localhost', 27017)
global base
base = client.league
def toMongo():
"""
receive a player object and save it
"""
def playersByPosition():
"""
query players by position
"""
def lineup():
"""
receive a team and return its starting line-up, players with primary = true
"""
答案 0 :(得分:0)
我是否需要将对象转换为Json(想到to_json方法)?
不,你不必。在您保存文档的问题的上下文中,您可以调用.save()这是因为底层MongoEngine将对象转换为BSON,因此您不必显式编写方法将其转换为JSON。 / p>
如果您想了解如何将MongoEngine对象转换为JSON,请参阅MongoEngine: Converting mongoengine objects to JSON #1 。
如何保存和查询?
请参阅插入示例MongoEngine Tutorial: Adding to our tumblelog:
p1 = Player(name='Caio', age=20)
p1.save()