我正在尝试使用Django REST Framework(3.3.1)生成JSON,它应使用直通模型对m2m字段进行排序。这适用于普通的django视图 - 订单受到尊重(即在管理列表中)。但是,使用标准DRF的ModelSerializers集合,django模型上指定的直通表不用于返回的m2m集的排序。
有没有一种简单的方法来实现我追求的顺序?或者我是否需要生成数据并返回我自己的DRF响应?
我有以下型号:
class Pitch(models.Model):
""" A pitch like 'A4" (A at octave 4) with midi note - ie 60 = middle C (C3) """
name = models.CharField(max_length=5)
midi_note = models.IntegerField()
def __unicode__(self):
return self.name
class Meta:
ordering = ['midi_note']
verbose_name_plural = 'pitches'
class Pattern(models.Model):
""" ie A Major """
name = models.CharField(max_length=50, default="")
pitches = models.ManyToManyField(Pitch, through='PitchPosition')
def __unicode__(self):
return u"{0}".format(self.name)
class PitchPosition(models.Model):
"""
The through table for a pitch in a pattern, needed as
scales/arpeggios go up and down, so pitches appear
twice in the list
"""
pattern = models.ForeignKey(Pattern)
pitch = models.ForeignKey(Pitch)
order = models.IntegerField(default=0)
def __unicode__(self):
return u"{0} ({1})".format(self.pitch, self.pattern)
class Meta:
ordering = ['pattern', 'order']
使用DRF序列化数据,直通表排序未得到遵守:
class PitchSerializer(serializers.ModelSerializer):
class Meta:
model = Pitch
fields = ('name', 'midi_note')
class PatternSerializer(serializers.ModelSerializer):
name = serializers.CharField()
pitches = PitchSerializer(many=True)
class Meta:
model = Pattern
fields = ('name', 'pitches')
产地:
[
{
"name": "D Major",
"pitches": [
{
"name": "D4",
"midi_note": 62
},
{
"name": "D4",
"midi_note": 62
},
{
"name": "E4",
"midi_note": 64
},
{
"name": "E4",
"midi_note": 64
},
{
"name": "F#4",
"midi_note": 66
},
{
"name": "F#4",
"midi_note": 66
},
{
"name": "G4",
"midi_note": 67
},
{
"name": "G4",
"midi_note": 67
},
{
"name": "A4",
"midi_note": 69
},
{
"name": "A4",
"midi_note": 69
},
{
"name": "B4",
"midi_note": 71
},
{
"name": "B4",
"midi_note": 71
},
{
"name": "C#5",
"midi_note": 73
},
{
"name": "C#5",
"midi_note": 73
},
{
"name": "D5",
"midi_note": 74
}
]
}
]