使用@post_dump通过棉花糖添加总行数吗?

时间:2019-02-26 16:21:37

标签: python-3.x postgresql sqlalchemy flask-sqlalchemy marshmallow

我需要添加此查询中返回的行数:

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列以获取总行数。

但是,由于它不是模型的一部分,我想知道在棉花糖中应该做什么,以便我可以添加行数(在RowCount列中)?

我以为可以用棉花糖@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

最奇怪的是,我的查询确实正确地返回了行数

enter image description here

有人可以帮我找出为什么我无法在post_dump方法中捕获行数键吗?

1 个答案:

答案 0 :(得分:0)

这需要通过棉花糖的pre_dump或post_dump方法来管理。但是实际上,我决定使用SQLAlchemy分页方法,因为它使响应中的行总数达到了