使用@post_dump 通过 Marshmallow 添加总行数?
Adding count of total rows through Marshmallow with @post_dump?
我需要添加此查询中返回的行数:
queryPostgres = db.text("""
SELECT *, COUNT(*) OVER () as RowCount
FROM (
SELECT * ,
( 3958.75 *
acos(sin(:lat1 / 57.2958) * sin( cast(latitude as double precision) / 57.2958) +
cos(:lat1 / 57.2958) * cos( cast(latitude as double precision) / 57.2958) *
cos( cast(longitude as double precision) / 57.2958 - :lon1/57.2958)))
as distanceInMiles
FROM "job" ) zc
WHERE zc.distanceInMiles < :dst
ORDER BY zc.distanceInMiles
LIMIT :per_page
OFFSET :offset
""")
jobs = cls.query.\
from_statement(queryPostgres). \
params(lat1=float(lat1),
lon1=float(lon1),
dst=int(dst),
per_page=int(per_page),
offset=int(offset))
return jobs
如您所见,我添加了 RowCount 列以获取总行数。
然而,由于它不是我模型的一部分,我想知道我应该在 Marshmallow 中做什么才能添加行数(在 RowCount 列中)?
我以为我可以用 Marshmallow @post_dump() 做到这一点,但是我不知道该怎么做。
为了更清楚起见,这里是我的架构。
class JobSchema(ma.ModelSchema):
def validate_state(state):
"""Validate one of 55 USA states"""
if state not in states:
raise ValidationError(INVALID_US_STATE)
def validate_zipCode(zip):
if not zipcodes.is_real(zip):
raise ValidationError(INVALID_ZIP_CODE)
@pre_load
def get_longitude_for_zipCode_and_TimeCreated(self, data):
""" This method will pass valids long,lat and time_created
values to each job created during a POST request"""
# Getting zip from the request to obtain lat&lon from DB
result = modelZipCode.getZipCodeDetails(data['zipCode'])
print(result)
if result is None:
raise ValidationError(INVALID_ZIP_CODE_2)
schema = ZipCodeSchema(exclude=('id'))
zip, errors = schema.dump(result)
if errors:
raise ValidationError(INVALID_ZIP_CODE_3)
else:
data['longitude'] = zip['longitude']
data['latitude'] = zip['latitude']
data['time_created'] = str(datetime.datetime.utcnow())
title = fields.Str(required=True, validate=[validate.Length(min=4, max=80)])
city = fields.Str(required=True, validate=[validate.Length(min=5, max=100)])
state = fields.Str(required=True, validate=validate_state)
zipCode = fields.Str(required=True, validate=validate_zipCode)
description = fields.Str(required=False, validate=[validate.Length(max=80)])
narrative = fields.Str(required=False, validate=[validate.Length(max=250)])
companyLogo = fields.Str(required=False, validate=[validate.Length(max=250)])
companyName = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
companyURL = fields.Str(required=True, validate=[validate.Length(min=4, max=100)])
latitude = fields.Str(required=True)
longitude = fields.Str(required=True)
time_created = fields.DateTime()
# We add a post_dump hook to add an envelope to responses
@post_dump(pass_many=True)
def wrap(self, data, many):
#import pdb; pdb.set_trace()
if len(data) >= 1:
counter = data[0]['RowCount']
return {
data,
counter
}
class Meta:
model = modelJob
最奇怪的是我的查询确实正确返回了行数
有人可以帮我找出为什么我无法在 post_dump 方法中捕获行计数键吗?
这需要由 Marshmallow pre_dump 或 post_dump method.But 管理,实际上我决定使用 SQLAlchemy 分页方法,因为它在响应中给出了总行数。
我需要添加此查询中返回的行数:
queryPostgres = db.text("""
SELECT *, COUNT(*) OVER () as RowCount
FROM (
SELECT * ,
( 3958.75 *
acos(sin(:lat1 / 57.2958) * sin( cast(latitude as double precision) / 57.2958) +
cos(:lat1 / 57.2958) * cos( cast(latitude as double precision) / 57.2958) *
cos( cast(longitude as double precision) / 57.2958 - :lon1/57.2958)))
as distanceInMiles
FROM "job" ) zc
WHERE zc.distanceInMiles < :dst
ORDER BY zc.distanceInMiles
LIMIT :per_page
OFFSET :offset
""")
jobs = cls.query.\
from_statement(queryPostgres). \
params(lat1=float(lat1),
lon1=float(lon1),
dst=int(dst),
per_page=int(per_page),
offset=int(offset))
return jobs
如您所见,我添加了 RowCount 列以获取总行数。
然而,由于它不是我模型的一部分,我想知道我应该在 Marshmallow 中做什么才能添加行数(在 RowCount 列中)?
我以为我可以用 Marshmallow @post_dump() 做到这一点,但是我不知道该怎么做。
为了更清楚起见,这里是我的架构。
class JobSchema(ma.ModelSchema):
def validate_state(state):
"""Validate one of 55 USA states"""
if state not in states:
raise ValidationError(INVALID_US_STATE)
def validate_zipCode(zip):
if not zipcodes.is_real(zip):
raise ValidationError(INVALID_ZIP_CODE)
@pre_load
def get_longitude_for_zipCode_and_TimeCreated(self, data):
""" This method will pass valids long,lat and time_created
values to each job created during a POST request"""
# Getting zip from the request to obtain lat&lon from DB
result = modelZipCode.getZipCodeDetails(data['zipCode'])
print(result)
if result is None:
raise ValidationError(INVALID_ZIP_CODE_2)
schema = ZipCodeSchema(exclude=('id'))
zip, errors = schema.dump(result)
if errors:
raise ValidationError(INVALID_ZIP_CODE_3)
else:
data['longitude'] = zip['longitude']
data['latitude'] = zip['latitude']
data['time_created'] = str(datetime.datetime.utcnow())
title = fields.Str(required=True, validate=[validate.Length(min=4, max=80)])
city = fields.Str(required=True, validate=[validate.Length(min=5, max=100)])
state = fields.Str(required=True, validate=validate_state)
zipCode = fields.Str(required=True, validate=validate_zipCode)
description = fields.Str(required=False, validate=[validate.Length(max=80)])
narrative = fields.Str(required=False, validate=[validate.Length(max=250)])
companyLogo = fields.Str(required=False, validate=[validate.Length(max=250)])
companyName = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
companyURL = fields.Str(required=True, validate=[validate.Length(min=4, max=100)])
latitude = fields.Str(required=True)
longitude = fields.Str(required=True)
time_created = fields.DateTime()
# We add a post_dump hook to add an envelope to responses
@post_dump(pass_many=True)
def wrap(self, data, many):
#import pdb; pdb.set_trace()
if len(data) >= 1:
counter = data[0]['RowCount']
return {
data,
counter
}
class Meta:
model = modelJob
最奇怪的是我的查询确实正确返回了行数
有人可以帮我找出为什么我无法在 post_dump 方法中捕获行计数键吗?
这需要由 Marshmallow pre_dump 或 post_dump method.But 管理,实际上我决定使用 SQLAlchemy 分页方法,因为它在响应中给出了总行数。