我需要保存可以包含许多宣传片,许多播放列表或许多apix_items的列表。列表的顺序'内容很重要,我收到的JSON将这些项目嵌套在'项目'
下的列表中apix_item列表:
{
"items": [
"rhmy5prfennp",
"lpi6ghwfwshp",
"scb6kn3hbqzd",
],
"title": "Apix Item List",
}
促销列表:
{
"items": [
{
"image": "some_url",
"id": "promo_1",
},
{
"image": "some_url",
"id": "promo_2"
}
],
"title": "Promo Item List"
}
我想使用ManyToMany关系,但我认为这不会起作用,因为列表'项目必须是通用的。所以我有一个非常简单的列表模型:
class List(TimeStamped):
title = models.CharField(max_length=255, default='New List')
以及具有ForeignKeyField和GenericForeignKey字段的中间ListOrder模型:
class ListOrder(TimeStamped):
content_types = {
'app_label__in': (
'apix_items',
'playlists',
'promos',
),
'model__in': (
'apix_item',
'playlist',
'promo',
),
}
index = models.PositiveIntegerField()
target_type = models.ForeignKey(ContentType, limit_choices_to=content_types)
target_object = GenericForeignKey('target_type', 'target_id')
target_id = models.PositiveIntegerField()
container = models.ForeignKey(List)
我有一种感觉,我需要在序列化程序中做一些疯狂的事情才能让它工作:
class ListOrderSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ListOrder
fields = (
'index',
'target_object',
'created',
'modified'
)
class ListSerializer(serializers.HyperlinkedModelSerializer):
items = ListOrderSerializer(many=True, required=False, source='list_order_set')
class Meta:
model = List
fields = (
'title',
'id',
'items',
'created',
'modified'
)
但是,我是Django和Django REST的新手,并且不知道从哪里开始。如何保存和检索这些通用的,有序的嵌套列表,保持中间ListOrder不可见?