1π
In your serializer, you can override the __new__
and __init__
magic methods like below:
class MySerializer(serializer.ModelSerializer):
def __new__(cls, *args, **kwargs):
kwargs.update({"has_many": kwargs.get("many", False)})
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
has_many = self.context["has_many"]
So, while you are serializing your data, you can anytime check if the serializer has been instantiated with the many=True/False
and, based on that, do what needs to be done.
π€xarhsasi
0π
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
request = kwargs['context']['request']
has_many = True if not request.parser_context["kwargs"].get('pk', None) else False
This is the workaround I have created. But not perfect. But does the job. If someone has a better answer which is working. Please share here.
π€Vishnu T
- [Answered ]-How can I upload two images in a form to 2 different directories in django?
- [Answered ]-How to track down a Python/Django/uwsgi/nginx timeout
- [Answered ]-Why is my django snippet not working?
Source:stackexchange.com