自定义序列化程序的字段显示

时间:2014-12-26 06:07:15

标签: python django serialization django-rest-framework

我有一个序列号:

class MovieShowtimeSerializer(serializers.ModelSerializer):
    class Meta:
        model = MovieShowtime
        fields = ( 'movietime', 'mvtype', )

resulti是:

        {
            "movietime": "2014-12-30T01:45:00Z", 
            "mvtype": "3D"
        }, 
        {
            "movietime": "2014-12-30T06:00:00Z", 
            "mvtype": "3D"
        }, 
        {
            "movietime": "2014-12-30T10:20:00Z", 
            "mvtype": "3D"
        }

我想知道它可以直接显示如下: 请帮帮我谢谢

        {
            "mvtype": "3D":{
                            "movietime": "2014-12-30T01:45:00Z", 
                            "movietime": "2014-12-30T06:00:00Z", 
                            "movietime": "2014-12-30T10:20:00Z", 
                            }

        }

models.py

class Showtime(models.Model):
    movietime       = models.DateTimeField(null=True,blank=True)
    mvtype          = models.CharField(max_length=255, blank=True)   

更新:我在下面编辑我的代码:

class MovieShowtimeSerializer(serializers.ModelSerializer):
    newshowtimes = serializers.SerializerMethodField('get_newshowtimes')
    def get_newshowtimes(self, obj):
        movietimes={}
        getmovietype = obj.mvtype
        if obj.mvtype not in movietimes:
            movietimes[getmovietype] = []
        movietimes[getmovietype].append(obj.movietime.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
        return movietimes
    class Meta:
        model = MovieShowtime
        fields = ( 'newshowtimes', )

结果:

"results": [
    {
        "newshowtimes": {
            "\u6578\u4f4d": [
                "2014-12-29T02:20:00.000000Z"
            ]
        }
    }, 
    {
        "newshowtimes": {
            "\u6578\u4f4d": [
                "2014-12-29T06:25:00.000000Z"
            ]
        }
    },       

但结果仍然不是我想要的 如何将两个新的时间结合起来:

"results": [
    {
        "newshowtimes": {
            "\u6578\u4f4d": [
                "2014-12-29T02:20:00.000000Z"
                "2014-12-29T06:25:00.000000Z"
            ]
        }
    },       

请帮帮我谢谢!

0 个答案:

没有答案