我有一个与房间相关的模型消息
class Message(models.Model):
room = models.ForeignKey(Room, on_delete=False, related_name='messages')
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
我的房间序列化器。
class RoomSerializer(serializers.ModelSerializer):
messages = MessageSerializer(read_only=True, many=True, allow_null=True)
class Meta:
model = Room
fields = '__all__'
当我获得room/10/
时,我得到所有消息的空间。没关系。但是我需要在今天,昨天和其他地方创建消息group_by。
最佳实践怎么样?也许它应该在前端完成,因为我只开发API?
示例:现在我得到了
{
"id": 10,
"messages": [{
"room": 10,
"text": "Messsage text",
"created": "2018-03-01T10:15:49.689655Z"
},
{
"room": 10,
"text": "Messsage text 2",
"created": "2018-03-02T10:15:49.689655Z"
}
]
}
我想得到这样的东西
{
"id": 10,
"messages": [{
"today": [{
"room": 10,
"text": "Messsage text",
"created": "2018-03-01T10:15:49.689655Z"
}]
},
{
"yesterday": [{
"room": 10,
"text": "Messsage text 2",
"created": "2018-03-02T10:15:49.689655Z"
}]
}
]
}
答案 0 :(得分:0)
我认为您最好选择使用serializers.SerializerMethodField
邮件:
import datetime
from itertools import groupby
class RoomSerializer(serializers.ModelSerializer):
messages = serializers.SerializerMethodField()
class Meta:
model = Room
fields = '__all__'
def get_messages(self, obj):
messages = obj.messages.all()
messages_grouped_by_date = groupby(messages.iterator(), lambda m: m.created.date())
messages_dict = {}
for date, group_of_messages in messages_grouped_by_date:
dict_key = date.strftime('%Y-%m-%d')
if date == datetime.date.today():
dict_key = 'today'
elif date == (datetime.date.today() - datetime.timedelta(days=1)):
dict_key = 'yesterday'
messages_dict[dict_key] = MessageSerializer(group_of_messages, many=True).data
return messages_dict