- Notifications
You must be signed in to change notification settings - Fork302
How to implement polymorphic serializer with non-ORM entities?#1034
-
My use case is that I am using a Example (very simplified and abstracted):
Example of data: [ {"id":"xxx","clothType":"tShirt","designer":"Mr. Designer","details": {"size":"L","color":"black" } }, {"id":"xxx","clothType":"pant","designer":"Mr. Designer Number 2","details": {"waist":22,"pantType":"slim" } }] |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 1 comment 2 replies
-
IF the model looks like classCloth(models.Model):cloth_type=models.JSONField() Then your serializer could looks like classClothSerializer(serilizers.ModelSerializer):cloth_type=SerializerMethodField()classMeta:model=Clothdefget_cloth_type(self,obj):# handles cloth type serializing in |
BetaWas this translation helpful?Give feedback.
All reactions
-
My main concern is includes and nested relationships. |
BetaWas this translation helpful?Give feedback.
All reactions
-
Hm - ok. Including and nested relationships are done by concrete django models i think. Maybe a maintainer of this project could tell us more about that. I would recommend you to modelling this on the django db layer like this: classCloth(PolymorphicModel):designer=models.CharField(max_length=256)classTShirt(Cloth):size=models.CharField(max_length=50,choices=["S","M","L", ])color=models.CharField(max_length=50,choices=["black","white"])classPath(Cloth):waist=models.CharField(max_length=50,choices=["22","23","24", ])pant_type=models.CharField(max_length=50,choices=["slim","regular"]) Then the only thing you need to do then is to write aPolymorphic serializer. I don't know anything about your constraints and why you want to use JSONFields instead of modelling concrete models and relations on the database. But in my experience with django in most cases it is better to modelling a concrete model instead of trying to implement generic things and put it in flat database fields. This is cause any site-package you will use is based on the django model concept (also this package too). I think you could save time if you first rethink about your django model layer instead of trying to hardly use site-packages for your solution if this is not really necessary. Your code base would also become more maintainable ;-) But this is just my opinion :-) feel free to implement a solution which matches your use cases. |
BetaWas this translation helpful?Give feedback.