How to Serialize SQL data after a Join using Marshmallow? (flask extension)

2024/11/18 17:37:01

I have 2 tables in SQL:

class Zoo(db.Model):id = db.Column(db.Integer, primary_key=True)nome = db.Column(db.String(80), unique=True, nullable=False)idade = db.Column(db.Integer, unique=False, nullable=False)peso = db.Column(db.Float, unique=False, nullable=False)cuidador = db.Column(db.Integer, db.ForeignKey('cuidador.id'))class Cuidador(db.Model):id = db.Column(db.Integer, primary_key=True)nome = db.Column(db.String(80), unique=True, nullable=False)animais = db.relationship('Zoo', backref='zoo', lazy=True)

And the Schemas defined:

class WorkerSchema(ma.SQLAlchemySchema):class Meta:model = Cuidadorid = ma.auto_field()nome = ma.auto_field()class ZooSchema(ma.SQLAlchemySchema):class Meta:model = Zooid = ma.auto_field()nome = ma.auto_field()idade = ma.auto_field()peso = ma.auto_field()cuidador = ma.Nested(WorkerSchema)

In a visualization route, I defined the following function to visualize the data present in the Zoo table:

def see_all_animals(self):result_join = db.session.query(Zoo,Cuidador).join(Zoo).all()zoo_schema = ZooSchema()result = zoo_schema.dump(result_join,many=True)return result

Unfortunately the function returns completely empty data. I would like something to appear along these lines:

{
...."id": 3,
...."idade": 5,
...."nome": "Cabra",
...."peso": 12.0,
...."cuidador": {"id":1,"nome":"Juan"}
}
Answer

The back reference of the database relationship used in your example adds a zoo attribute to objects of the Zoo type, under which the referenced Cuidador object can be queried.
For the currently used database modeling, I recommend the following marshmallow schemas. This involves renaming the back reference defined by the database relationship from "zoo" to "cuidador".

class WorkerSchema(ma.SQLAlchemyAutoSchema):class Meta:model = Cuidadorclass ZooSchema(ma.SQLAlchemyAutoSchema):class Meta:model = Zoocuidador = ma.Nested(WorkerSchema, attribute='zoo')

It is not necessary to actively use a join statement to achieve the desired output. Due to the defined relationship and the nested schema, the query and formatting of the referenced data takes place automatically.

def index():zoos = Zoo.query.all()zoos_schema = ZooSchema(many=True)zoos_data = zoos_schema.dump(zoos)return jsonify(data=zoos_data)

The output obtained here is now the following.

{"data": [{"cuidador": {"id": 1, "nome": "Juan"}, "id": 1, "idade": 5, "nome": "Cabra", "peso": 12.0}]
}

I advise you to pay more attention to naming when modeling to avoid unnecessary renaming and to deepen your knowledge of database relationships. The correct representation of relationships and the avoidance of duplicates in naming will help you with further and larger projects, in which I wish you a lot of fun.

https://en.xdnf.cn/q/118643.html

Related Q&A

Python readline() is not reading a line with single space

I am reading a text file using readline(). My file contains below content with a space at second line:!" # $ % & When I print read values using-print("%s\n" % iso5_char)It prints-!&q…

Bisection search [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:Using bisection search to determine I have posted other thread but it did not receive answers thus im trying to provide so…

What am i doing wrong with matplotlibs yticks?

My code is as follows (dont ask for the variable names, im german^^):import matplotlib.pyplot as plt import numpy as np strecke = [] zeit = []daten = open("BewegungBeschleunigung.csv")for i i…

Python- How to implement quick sort when middle element is the pivot?

There are many different versions of quickSort that pick pivot in different ways.Always pick the first element or the last element as the pivot Pick a random element as a pivot. Pick median as the pivo…

How to expose a form when a radio button is checked?

Consider the following sample html template,<html><body><input type="radio" name="x">x</input><br><input type="radio" name="y"&g…

How to generate perlin noise in pygame?

I am trying to make a survival game and I have a problem with perlin noise. My program gives me this:But I want something like islands or rivers. Heres my code: #SetUp# import pygame, sys, random pygam…

Inputting range of ports with nmap optparser

This is the scriptimport nmap import optparsedef nmapScan(tgtHost,tgtPort):nmScan = nmap.PortScanner()nmScan.scan(tgtHost,tgtPort)state=nmScan[tgtHost][tcp][int(tgtPort)][state]print "[*] " +…

Implementing a Python algorithm for solving the n-queens problem efficiently

I am working on a project that requires me to solve the n-queens problem efficiently using Python. I have already implemented a basic recursive algorithm to generate all possible solutions, but I am lo…

Annotations with pointplot

I am using a pointplot in seaborn.import seaborn as sns sns.set_style("darkgrid") tips = sns.load_dataset("tips") ax = sns.pointplot(x="time", y="total_bill", hu…

How do I get data in tuples and tuples in lists?

I am trying to figure out the route that a car takes in a fictional manhattan. I have defined the starting position, being(1,2)(in a 2 dimensional grid).manhattan=[[1, 2, 3, 4, 5],[6, 7, 8, 9, 10],[11…