Я хочу создать отношение «один ко многим», скажем, у меня есть базовая таблица пользователей со связью с другой таблицей, называемой «обычный пользователь», когда я хочу получить данные обычного пользователя и показать рядом с ним данные базового пользователя работает нормально, но когда я хочу обновить обе детали вместе, это не позволяет мне, а также заставляет меня обновлять все элементы таблицы, как это преодолеть, пожалуйста, и позволяет мне обновлять отдельные запросы вместо отправки всего данные?
Ресурс пользователя:
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
from models.users import UserModel
from models.base_user import BaseuserModel
class User(Resource):
parser = reqparse.RequestParser()
parser.add_argument('nickname',
type=str,
required=True,
help="You can't keep nickname empty."
)
parser.add_argument('dob',
type=str,
required=True,
help="You can't keep dob empty."
)
parser.add_argument('bio',
type=str,
required=True,
help="You can't keep bio empty."
)
parser.add_argument('career',
type=str,
required=True,
help="You can't keep career empty."
)
@jwt_required()
def get(self, create):
user = UserModel.find_by_baseuserid(baseuser_id)
if user:
return user.json()
return {'message': 'user not found'}, 404
def post(self, baseuser_id):
if UserModel.find_by_baseuserid(baseuser_id):
return {'message': "An user with baseuser id '{}' already exists.".format(baseuser_id)}, 400
data = User.parser.parse_args()
user = UserModel(baseuser_id, **data)
try:
user.save_to_db()
except:
return {"message": "An error occurred inserting the item."}, 500
return user.json(), 201
def delete(self, baseuser_id):
user = UserModel.find_by_baseuserid(baseuser_id)
if user:
user.delete_from_db()
return {'message': 'user deleted.'}
return {'message': 'User not found.'}, 404
def put(self, baseuser_id):
data = Updateuser.parser.parse_args()
# data = BaseUserRegister.parser.parse_args()
user = UserModel.find_by_baseuserid(baseuser_id)
baseuser = BaseuserModel.find_by_id(baseuser_id)
if user:
user.nickname = data['nickname']
user.dob = data['dob']
user.bio = data['bio']
user.career = data['career']
else:
user = UserModel(baseuser_id, **data)
user.save_to_db()
return user.json(), baseuser.json()
class UserList(Resource):
def get(self):
return {'users': list(map(lambda x: x.json(), UserModel.query.all()))}
ресурс базового пользователя:
from flask_restful import Resource, reqparse
from models.base_user import BaseuserModel
class BaseUserRegister(Resource):
parser = reqparse.RequestParser()
parser.add_argument('username',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('password',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('lat',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('lng',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('address',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('phone',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('email',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('social_type',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('social_id',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('profile_image_url',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument('account_type',
type=str,
required=True,
help="This field cannot be blank."
)
def post(self):
data = BaseUserRegister.parser.parse_args()
if BaseuserModel.find_by_username(data['username']):
return {"message": "A user with that email already exists"}, 400
user = BaseuserModel(data['username'], data['password'], data['lat'],
data['lng'],
data['address'], data['phone'], data['email'], data['social_type'],
data['social_id'], data['profile_image_url'], data['account_type'])
# user = UserModel(**data)
user.save_to_db()
return {"message": "User created successfully."}, 201
модель пользователя:
from db import db
class UserModel(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
baseuser_id = db.Column(db.Integer, db.ForeignKey('baseusers.id'))
baseuser = db.relationship('BaseuserModel')
nickname = db.Column(db.String(80))
dob = db.Column(db.String(80))
bio = db.Column(db.String(80))
career = db.Column(db.String(80))
def __init__(self, baseuser_id, nickname, dob, bio, career):
self.baseuser_id = baseuser_id
self.nickname = nickname
self.dob = dob
self.bio = bio
self.career = career
def json(self):
return {'baseuser_id': self.baseuser_id,
'username': self.baseuser.username, 'lat': self.baseuser.lat,
'lng': self.baseuser.lng, 'address': self.baseuser.address,
'phone': self.baseuser.phone, 'email': self.baseuser.email,
'profile_image_url': self.baseuser.profile_image_url, 'nickname': self.nickname,
'dob': self.dob, 'bio': self.bio, 'career': self.career}
@classmethod
def find_by_baseuserid(cls, baseuser_id):
return cls.query.filter_by(baseuser_id=baseuser_id).first()
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
базовая модель пользователя:
from db import db
class BaseuserModel(db.Model):
__tablename__ = 'baseusers'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
password = db.Column(db.String(80))
lat = db.Column(db.String(255))
lng = db.Column(db.String(255))
address = db.Column(db.String(255))
phone = db.Column(db.String(80))
email = db.Column(db.String(80))
social_type = db.Column(db.String(80))
social_id = db.Column(db.String(80))
profile_image_url = db.Column(db.String(255))
account_type = db.Column(db.String(80))
user = db.relationship('UserModel', lazy='dynamic')
facility = db.relationship('FacilityModel', lazy='dynamic')
def __init__(self, username, password, lat, lng, address, phone, email, social_type, social_id, profile_image_url, account_type):
self.username = username
self.password = password
self.lat = lat
self.lng = lng
self.address = address
self.phone = phone
self.email = email
self.social_type = social_type
self.social_id = social_id
self.profile_image_url = profile_image_url
self.account_type = account_type
def json(self):
return {'baseuser_id': self.id,
'username': self.username, 'lat': self.lat, 'lng': self.lng,
'address': self.address, 'phone': self.phone, 'email': self.email,
'social_type': self.social_type, 'social_id': self.social_id,
'profile_image_url': self.profile_image_url}
def save_to_db(self):
db.session.add(self)
db.session.commit()
# @classmethod
# def find_by_baseuserid(cls, _id):
# return cls.query.filter_by(id=_id).first()
@classmethod
def find_by_id(cls, _id):
return cls.query.filter_by(id=_id).first()
@classmethod
def find_by_username(cls, username):
return cls.query.filter_by(username=username).first()