Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I cache a variable in ModelSchema? #1345

Open
pyang30 opened this issue Nov 26, 2024 · 1 comment
Open

Can I cache a variable in ModelSchema? #1345

pyang30 opened this issue Nov 26, 2024 · 1 comment

Comments

@pyang30
Copy link

pyang30 commented Nov 26, 2024

code like this: I query SomeMode three times to get a OutSchema, Question: Can I cache the 'x' result to reduce db query?

class  OutSchema(ModelSchema):
    out_a: str
    out_b: str,
    out_c: str
    class Config:
         model = M

    @staticmethod
    def resolve_out_a(obj):
            x = SomeModel.objects.get(name=obj.xxx)
            return x.out_a

    @staticmethod
    def resolve_out_b(obj):
            x = SomeModel.objects.get(name=obj.xxx)
            return x.out_b

    @staticmethod
    def resolve_out_c(obj):
            x = SomeModel.objects.get(name=obj.xxx)
            return x.out_c
@vitalik
Copy link
Owner

vitalik commented Nov 26, 2024

@pyang30 well either use builtin django cacheing functions or just cache it as an attrribute on your obj:

class  OutSchema(ModelSchema):
    ...

    @staticmethod
     def get_somemodel_x(obj):
         if not hasattr(obj, '_x'):
             obj._x = SomeModel.objects.get(name=obj.xxx)
         return obj._)x
            
    @staticmethod
    def resolve_out_a(obj):
         return OutSchema.get_somemodel_x(obj).out_a

    @staticmethod
    def resolve_out_b(obj):
         return OutSchema.get_somemodel_x(obj)..out_b

    @staticmethod
    def resolve_out_c(obj):
         return OutSchema.get_somemodel_x(obj)..out_c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants