How to create tuple with key receiving value?

Asked

Viewed 131 times

0

I would like to create a method that returns the Django ORM FILTER parameters. I will have to use these filters at various times, I would like to create this generic method. Follow the example:

def home(selected_page=None):
    _config = Config.objects.filter()
    _config = _config.filter(filter_config_by_page(selected_page))
    return _config

def filter_config_by_page(selected_page):
    final_tuple = ()
    if selected_page == "work":
        final_tuple = (works__user__isnull = False,)
    elif selected_page == "not-work":
        final_tuple = (works__user__isnull = True,)
    elif selected_page == "solved":
        final_tuple = (status = 2,)
    elif selected_page == "not-solved":
        final_tuple = (status = 3,)
    return final_tuple

Error

File "/myapp/configuerson/controller/configs.py", line 101
    final_tuple = (works__user__isnull = False,)
                                         ^
SyntaxError: invalid syntax

I believe, according to the error that came up, that I can’t assign value to tuples that I’m creating that way. Would there be some way to do the filter_config_by_page work following this logic I described?

  • 1

    Now that I see that you want to create a filter for Django, I’ll read the documentation and, if you can understand how it works, I put something here.

  • Yes, a method just to build the Django filter. Thank you

1 answer

0

Instead of returning a tuple, you can return a dictionary with the parameters you want to use in the filter. Then just expand the dictionary using **:

def home(selected_page=None):
    _config = Config.objects.filter()
    kwargs = filter_config_by_page(selected_page)
    _config = _config.filter(**kwargs)
    return _config

def filter_config_by_page(selected_page):
    final_tuple = {}
    if selected_page == "work":
        final_tuple = {"works__user__isnull": False}
    elif selected_page == "not-work":
        final_tuple = {"works__user__isnull": True}
    elif selected_page == "solved":
        final_tuple = {"status": 2}
    elif selected_page == "not-solved":
        final_tuple = {"status": 3}
    return final_tuple

Browser other questions tagged

You are not signed in. Login or sign up in order to post.