Question:
Avoid code duplication between django Q expression and Python

Problem:


from enum import Flag


class Color(Flag):

    RED = 1

    BLUE = 2

    GREEN = 4

    WHITE = RED | BLUE | GREEN # <- How do I retrieve this alias?


list(Color) 

# [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 4>]

# How do I include Color.White and other aliases in this list?

From documentation, __iter__ returns only non-alias members.

__iter__(self):

Returns all contained non-alias members

Changed in version 3.11: Aliases are no longer returned during iteration.


Solution:

You can use >__members__ to get a mapping of enum name to value.

From python >docs:


__members__ is a read-only ordered mapping of member_name:member items. It is only available on the class.


mapping = Color.__members__

# mappingproxy({'RED': <Color.RED: 1>,

#              'BLUE': <Color.BLUE: 2>,

#              'GREEN': <Color.GREEN: 4>,

#              'WHITE': <Color.WHITE: 7>})


colors_list = list(mapping.values())

# [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 4>, <Color.WHITE: 7>]


There's a caveat to this though. If you have enum values that are similar then you'd get the same value returned for them.

class Color(Flag):

    RED = 1

    BLUE = 1

print(Color.__members__)

# mappingproxy({'RED': <Color.RED: 1>, 'BLUE': <Color.RED: 1>})


Suggested blogs:

>Fix webapp stops working issue in Django- Python webapp

>Creating a form in Django to upload a picture from website

>Sending Audio file from Django to Vue

>How to keep all query parameters intact when changing page in Django?

>Solved: TaskList View in Django

>Implement nested serializers in the Django rest framework

>Define blade component property in server - Laravel


Ritu Singh

Ritu Singh

Submit
0 Answers