Filter Nested field in Flask Marshmallow

2024/10/11 0:26:03

I want to filter the nested field with is_active column as True in Marshmallow 3 Consider following scenario I have 3 tables

users (id, name)
organizations (id, name)
organization_user(id, organization_id, user_id, is_active)

Now I'm trying to print all the organization with its members who are active. (There are some active and inactive members)

I have following schema

class OrganizationSchema(ma.ModelSchema):members_list = fields.Nested(OrgnizationUserSchema, many=True, exclude=('checklist', ))class OrgnizationUserSchema(ma.ModelSchema):user_list = fields.Nested(UserSchema)

Now in my action following is the code

organization_schema = OrganizationSchema(many=True)
#Query for list of organization
organization_list = Organization.query.all()
organization_schema.dump(organization_list)

Following is Output

[{'id': 1,'name': 'abc','members_list': [{'id':1, 'organization_id': 1, 'user_id':1, 'is_active':True},{'id':1, 'organization_id': 1, 'user_id':2, 'is_active':False}]}
]

I want output with member who has 'is_active':True as follows

[{'id': 1,'name': 'abc','members_list': [{'id':1, 'organization_id': 1, 'user_id':1, 'is_active':True}]}
]

Marshmallow provides a decorator @post_dump. Problem here is Query brings all data and then we filter it with decorator @post_dump. But the flow should be like, while querying there should be some way to filter the data and not post query filtering.

Answer

I went the other way. I have cloths, designs and remainders. For each fabric I need to get all the designs, and for each design will get the remainders for the specified city.

class ClothSchema(Schema):id = fields.Integer(dump_only=True)name = fields.String(validate=not_blank)type = fields.Nested(ClothTypeSchema)designs = fields.Nested(DesignSchema, many=True)class DesignSchema(Schema):id = fields.Integer(dump_only=True)name = fields.String(validate=not_blank)remainders = fields.Nested(RemainderSchema, many=True)class RemainderSchema(Schema):id = fields.Integer(dump_only=True)value = fields.String()city = fields.String()

I get the data I need in the controller so that they are not requested on the go.

    db.session.query(Cloth).join(Cloth.designs).join(Design.remainders).filter(Remainder.city == city).options(contains_eager("designs").contains_eager("remainders"))

As a result, I get all the cloths and all the designs for which the remainders are given. If no design remainders are indicated, it will not be displayed.

{"attributes": {"designs": {"data": [{"attributes": {"name": "Amely 10 ", "remainders": {"data": [{"attributes": {"city": "CityEnum.MOSCOW", "value": "333"}, "id": 9318, "type": "remainder"}]}}, "id": 365, "type": "design"} ], "links": {"self": "/designs"}}, "name": "Amely", "rapport": null, "type": {} }, "id": 22, "type": "cloth"
}
https://en.xdnf.cn/q/69838.html

Related Q&A

Copy signature, forward all arguments from wrapper function

I have two functions in a class, plot() and show(). show(), as convenience method, does nothing else than to add two lines to the code of plot() likedef plot(self,show_this=True,show_that=True,color=k,…

How to fit a line through a 3D pointcloud?

I have a cable I am dropping from moving vehicle onto the ground. Using a camera system I estimate the location where the rope touches the ground in realtime. Movement of the vehicle and inaccuracy in …

Websockets with Django Channels on Heroku

I am trying to deploy my app to heroku. The app has a simple chatting system that uses Websockets and django channels. When I test my app using python manage.py runserver the app behaves just as intend…

How can I get the name/file of the script from sitecustomize.py?

When I run any Python script, I would like to see the scripts filename appear in the Windows command line windows titlebar. For example, if I run a script called "mytest.py", I want to see &q…

Sending Godaddy email via Django using python

I have these settings EMAIL_HOST = smtpout.secureserver.net EMAIL_HOST_USER = [email protected] EMAIL_HOST_PASSWORD = password DEFAULT_FROM_EMAIL = [email protected] SERVER_EMAIL = [email protected] EM…

python math, numpy modules different results?

I get slightly different results calculating the cosine of a value. How can I check that this difference is within machine precision?import math math.cos(60.0/180.0*math.pi) -> 0.5000000000000001im…

How to extract equation from a polynomial fit?

My goal is to fit some data to a polynomial function and obtain the actual equation including the fitted parameter values. I adapted this example to my data and the outcome is as expected. Here is my c…

python dictionary conundrum

On the console I typed in>>> class S(str): pass ... >>> a = hello >>> b = S(hello) >>> d = {a:a, b:b} >>> d {hello: hello} >>> type(d[a]) <class…

Celery 4 not auto-discovering tasks

I have a Django 1.11 and Celery 4.1 project, and Ive configured it according to the setup docs. My celery_init.py looks likefrom __future__ import absolute_importimport osfrom celery import Celery# set…

Is it possible to use a custom filter function in pandas?

Can I use my helper function to determine if a shot was a three pointer as a filter function in Pandas? My actual function is much more complex, but i simplified it for this question.def isThree(x, y…