Giter VIP home page Giter VIP logo

Comments (5)

NickWoodhams avatar NickWoodhams commented on August 20, 2024

I also noticed this, I ended up adding all the relational items to json_hidden

I would be interested in your answer as well.

Nick

from overholt.

mattupstate avatar mattupstate commented on August 20, 2024

I understand that the JsonSerializer class has some pitfalls when it comes to relationship fields with SQLAlchemy. In your case the users attribute, which is added via the backref, is not a list but an AppenderBaseQuery. In this case you can use the __json_modifiers__ attribute to marshal that field in the way you wish. For example:

class ProjectJsonSerializer(JsonSerializer):
    __json_modifiers__ = {
        'users': lambda users, _: [dict(id=user.id) for user in users]
    }

This will render a JSON response like such:

{
    "id": 1,
    "name": "project name",
    "users": [
        {
            "id": 1
        },
        {
            "id": 2
        }
    ]
}

Adjust the modifier to your liking to render the appropriate JSON object.

from overholt.

scottwernervt avatar scottwernervt commented on August 20, 2024

Thanks Matt, that worked perfectly! I now have a better understanding of lambda after reading some tutorials and from your answer.

from overholt.

NickWoodhams avatar NickWoodhams commented on August 20, 2024

Great answer by the way. Thanks for sharing.

from overholt.

boxcarcoder avatar boxcarcoder commented on August 20, 2024

Hi Matt, firstly I appreciate you making this template an open source project. It has really helped me understand serializing alembic models into JSON format.

I am trying to better understand your JSONSerializer class and the JSON modifier you provided in this issue. Can you tell me if I am understanding the logic for the to_json() function correctly? Given the following classes:

class JsonSerializer(object):
    
    __json_modifiers__ = None


    def to_json(self):

        modifiers = self.__json_modifiers__ or dict()

        rv = dict()

        for key, modifier in modifiers.items():
            value = getattr(self, key)
            rv[key] = modifier(value, self)

        return rv

# My own modified json serializer
class SubredditJsonSerializer(JsonSerializer):
    """
    Extend the JsonSerializer class to change the users attribute from type
    AppenderBaseQuery to type list.
    """
    __json_modifiers__ = {
        'users': lambda users, _: [dict(id=user.id, username=user.username, phone_num=user.phone_num) for user in users]
    }

The following is my understanding of how the code is executing:

    def to_json(self):

        # modifiers == {
        #   'users': lambda users, _: [dict(id=user.id, username=user.username, phone_num=user.phone_num) for user in users]
        # }
        modifiers = self.__json_modifiers__ or dict()

        rv = dict()


        # modifiers.items() == [
        #   ('users', lambda users, _: [dict(id=user.id, username=user.username, phone_num=user.phone_num) for user in users])
        # ]
        for key, modifier in modifiers.items():

            # key == 'users'
            # value == lambda users, _: [dict(id=user.id, username=user.username, phone_num=user.phone_num) for user in users]
            value = getattr(self, key)


            ## This is the step I am having trouble understanding. How is modifier being used as a function if it is a key-value pair?

            # modifier == ('users', lambda users, _: [dict(id=user.id, username=user.username, phone_num=user.phone_num) for user in users])
            # rv['users'] = ???
            rv[key] = modifier(value, self)

        return rv

Am I understanding the execution correctly?

from overholt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.