如何使用 marshmallow_sqlalchemy 定义 marshamllow 列表字段

问题描述

我正在尝试使用 marshmallow_sqlalchemy 创建架构。我想从数据库的两个条目 x_coordinate 和 y_coordinate 中创建一个列表,但是,我不知道该怎么做。

这是架构

from marshmallow_sqlalchemy import sqlAlchemySchema,auto_field
class LocationsqlAlchemySchema(sqlAlchemySchema):
    class Meta:
        model = Location
        load_instance = True
    
    location_id = auto_field('id')
    name = auto_field('name')
    user_uid = auto_field('customer_id')
    maps_url = auto_field('maps_url')
    coordinates = fields.List(Meta.model.x_coordinate,Meta.model.y_coordinate) #This is what I don't kNow how to define.

这是我用于此架构的模型:

from flask_sqlalchemy import sqlAlchemy
from sqlalchemy.dialects.MysqL import INTEGER
db = sqlAlchemy()
class Location(db.Model):
    __tablename__ = 'cleaning_locations'
    id = db.Column(db.String(128),primary_key=True,unique = True)
    name =  db.Column(db.String(45),nullable = False)
    customer_id = db.Column(db.String(45),nullable = False)
    maps_url = db.Column(db.String(2048),nullable = False)
    x_coordinate = db.Column(db.Numeric(precision = 8,scale=5),nullable = False)
    y_coordinate = db.Column(db.Numeric(precision = 8,nullable = False)
    address = db.Column(db.String(255))
    country = db.Column(db.String(45))
    state = db.Column(db.String(45))
    size = db.Column(INTEGER(unsigned=True),nullable = False )
    rooms = db.Column(INTEGER(unsigned=True),nullable = False )
    bathrooms = db.Column(INTEGER(unsigned=True),nullable = False )
    kitchens = db.Column(INTEGER(unsigned=True),nullable = False )

  1. 如何让 Schema 将坐标表示为包含 x_coordinate 和 y_coordinate 的列表?
  2. (新手额外问题)。在 db 模型和 Schema 中使用不同的变量名是一种不好的做法吗?

解决方法

请试试这个(未经测试):

from marshmallow_sqlalchemy import field_for

[...]

coordinates = fields.Tuple(
    (field_for(Location,"x_coordinate"),field_for(Location,"y_coordinate"))
)

不确定这是最好的主意,因为那样你就不能把从模式加载的数据塞进对象 init 中。但是没有什么可以阻止您拥有与数据库表示不同的 API(架构)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...