[英]Django Rest Framework - Interrelated serializers
給定以下模型,其中兩個模型與第一個模型具有ManyToMany關系,如何為所有三個模型構造序列化器?
這就是在Python中進行排序的重要性正成為一個問題的地方。
class Trail(models.Model):
'''
Main model for this application. Contains all information for a 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):
'''
A many to many join table to map an activity name to a trail. A 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):
'''
A many to many join table to map a surface type to many trails. A 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', )
我在serializers.py中有以下序列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', )
我的問題是,沒有創建另一個包含ActivitySerializer and SurfaceSerializer
文件,我如何確保TrailSerializer
可以按預期工作,以便在序列化期間包括Activity和Surface引用?
使用棉花糖 (序列化庫部分受DRF序列化程序啟發)。 通過允許將嵌套模式作為字符串引用來解決此問題。 參見棉花糖:雙向嵌套
class AuthorSchema(Schema):
# Make sure to use the 'only' or 'exclude' params to 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')
您可以直接使用,也可以通過Tom Christie的 django-rest-marshmellow使用,它允許使用棉花糖,同時保持與REST框架的Serializer
類相同的API。
我不知道僅使用DRF序列化器即可達到相同結果的方法。
另請參閱: 為什么選擇棉花糖?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.