I am using direct examples from the Django REST framework tutorial, I have 2 classes: UserSerializer and SnippetSerializer. I want to be able to use UserSerializer as a serializer in the SnippetSerializer class declaration, but for reasons, SnippetSerializer needs to be declared first.
Code example:
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = UserSerializer()
#unimportant stuff
class UserSerializer(serializers.HyperlinkedModelSerializer):
#unimportant stuff - lets say we reference SnippetSerializer here
The obvious answer that comes to mind is a forward declaration, but from all my research, I cannot find this in Python.
Another solution I thought might work, which didn't (perhaps I did it wrong?) is instead trying to declare this relationship in the init method
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
def __init__(self, *args, **kwargs):
self.owner = UserSerializer()
super(SnippetSerializer, self).__init__(*args, **kwargs)
But this seemed to be completely ignored by the framework.
I also tried using the @addto, but it seems it only works for functions, not attributes/properties
Is there a way around this problem? This chicken-before-egg class problem has been killing me in Python for a while, but I've finally run into an instance where it is actually stopping me from getting the job done.
You may be able to provide a string containing the (dot notation) path to the class, instead.
Using DRF, you may have a folder structure like so:
├── appname
│ ├── ...
│ └── serializers.py
├── ...
SnippetSerializer and UserSerializer declared inside the above serializers.py file.
You'd then reference UserSerializer using the string: "appname.serializers.UserSerializer" where you'd normally write UserSerializer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With