python - Django Rest Framework - Interrelated serializers -
given following models 2 have manytomany relationship first, how can construct serializer 3 models?
this importance of ordering in python turning issue.
class trail(models.model): ''' main model application. contains information particular trail ''' trail_name = models.charfield(max_length=150) active = models.booleanfield(default=true) date_uploaded = models.datetimefield(default=now()) owner = models.foreignkey(account, default=1) class meta: ordering = ('trail_name', ) class activity(models.model): ''' many many join table map activity name trail. trail can have many activities ''' name = models.charfield(max_length=40, unique=true) trails = models.manytomanyfield(trail) class meta: ordering = ('name', ) class surface(models.model): ''' many many join table map surface type many trails. trail can have many surface types. ''' type = models.charfield(max_length=50, db_column='surface_type', unique=true) trails = models.manytomanyfield(trail) class meta: ordering = ('type', )
i have following serializers in serializers.py
:
class trailserializer(serializers.modelserializer): owner = accountserializer() activities = activityserializer() class meta: model = trail fields = ('trail_name', 'active', 'date_uploaded', 'owner', 'activities', ) class activityserializer(serializers.modelserializer): trails = trailserializer() class meta: model = activity fields = ('trails', 'name', ) class surfaceserializer(serializers.modelserializer): trails = trailserializer() class meta: model = surface fields = ('trails', 'type', )
my question is, short of creating file contain activityserializer , surfaceserializer
, how can ensure trailserializer
works expected in order include activity , surface references during serialization?
use marshmallow (serialization library inspired in part drf serializers). solves problem, allowing nested schemas reference strings. see marshmallow: 2 way nesting
class authorschema(schema): # make sure use 'only' or 'exclude' params avoid infinite recursion books = fields.nested('bookschema', many=true, exclude=('author', )) class meta: fields = ('id', 'name', 'books') class bookschema(schema): author = fields.nested(authorschema, only=('id', 'name')) class meta: fields = ('id', 'title', 'author')
you can use directly or use via django-rest-marshmellow tom christie, allows use of marshmallow, while maintaining same api rest framework's serializer
class.
i'm not aware of way achieve same result using drfs serializers.
see also: why marshmallow?
Comments
Post a Comment