I have a user model that has a set of notifications:
class User(AbstractUser):
# Notification flags
send_to_all = models.BooleanField(default=True)
send_to_me = models.BooleanField(default=True)
send_to_friends = models.BooleanField(default=True)
# ...
I am passing them from front-end to my views where I trigger send_notifications function.
# ...
def update(self, request, *args, **kwargs):
# ...
send_notifications(request.data.get('send_to_all', False))
# ...
And in the send_notifications I want to query User.objects.filter() and inlcude only those that have the flag passed from front-end set to True.
My question is:
Is there any way to simplify it? I am asking because there is many notifications options, like 20. And currently my code has 20 ifs:
def send_notifications(flag):
if flag == 'send_to_all':
users_to_send = User.objects.filter(send_to_all=True)
if flag == 'send_to_me':
users_to_send = User.objects.filter(send_to_me=True)
if flag == 'send_to_friends':
users_to_send = User.objects.filter(send_to_friends=True)
if flag == 'another_send_flag':
users_to_send = User.objects.filter(another_send_flag=True)
if flag == 'another_send_flag':
users_to_send = User.objects.filter(another_send_flag=True)
Thanks!
CodePudding user response:
You can wrap User.objects.filter()
with eval like that:
users_to_send = eval(f"User.objects.filter({flag}=True)")