我目前正在将QuerySet的结果放入我的js前端使用的JSON字符串中.
目前使用.values()和simplejson很容易:
simplejson.dumps(list(Task.objects.filter(list=mylist).values()))
Run Code Online (Sandbox Code Playgroud)
我现在在我的Task对象中添加了一个ManyToMany字段,希望将它包含在我的输出中,而不必为ManyToMany关系的每个值重复每个Task对象.
如果我只是做了Task.objects.filter(list=mylist).values('myManyToManyField', 'someOtherField') 输出将为每个值有一个单独的对象/行myManyToManyField
[{'myManyToManyField': 1, 'someOtherField': 'valueOne'},
{'myManyToManyField': 2, 'someOtherField': 'valueOne'},
{'myManyToManyField': 1, 'someOtherField': 'valueTwo'}]
Run Code Online (Sandbox Code Playgroud)
有没有办法得到这个结果?:
[{'myManyToManyField': [1,2], 'someOtherField': 'valueOne'},
{'myManyToManyField': 1, 'someOtherField': 'valueTwo'}]
Run Code Online (Sandbox Code Playgroud)
我现在唯一的解决方案是遍历所有Task对象并手动构建输出,根据需要将ManyToMany值放在其中.有一个更好的方法吗?如果不是 - 这会非常低效吗?
模型:
class Genre(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Song(models.Model):
name = models.CharField(max_length=200)
genre = models.ManyToManyField(Genre)
Run Code Online (Sandbox Code Playgroud)
序列化器:
class GenreSerializer(serializers.ModelSerializer):
class Meta:
model = Genre
fields = '__all__'
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Song
fields = '__all__'
def to_representation(self, instance):
rep = super().to_representation(instance)
print(GenreSerializer(instance.name).data)
return rep
Run Code Online (Sandbox Code Playgroud)
序列化程序中的上述打印给出: {'name': None} 并且响应使用流派 ID 而不是值:
[
{
"id": 1,
"name": "Abcd",
"genre": [
1,
3
]
}
]
Run Code Online (Sandbox Code Playgroud)
其中流派1. 流行,3. 摇滚
我可以对 to_representation 进行哪些更改以打印值而不是流派的 id,流派是具有歌曲模型的 ManyToManyField。