我的序列化程序返回索引而不是实际字段

时间:2018-01-20 10:33:06

标签: django python-3.x serialization django-rest-framework django-serializer

我是Django的新手,我一直在尝试序列化名为MoviesCategories的模型对象。

class MoviesCategories(models.Model):
    name = models.CharField(max_length=120, null=False)

    def __str__(self):
        return self.name

还有一个Movie模型如下

class Movie(models.Model):
    name = models.CharField(max_length=120, null=False)
    thumbnail = models.CharField(max_length=120, null=False)
    source_url = models.CharField(max_length=500, null=False)
    duration = models.TimeField(default=timedelta(hours=2))
    added_on = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey(MoviesCategories, related_name="movies", on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('added_on',)

我的MoviesCategoriesSerializer看起来像这样

class MoviesCategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = MoviesCategories
        fields = ('name', 'movies')

当我这样做时,我从这个序列化器中得到了什么 MoviesCategoriesSerializer(MoviesCategories.objects.first()).data {'movies': [1, 2], 'name': 'Animations'}  我希望能得到电影领域。我创建了一个MovieSerializer

class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('name', 'thumbnail', 'source_url', 'duration') 但我不知道如何将这两者联系起来 MoviesCategoriesSerializer(MoviesCategories.objects.first()).data 返回第一类

中的所有电影

1 个答案:

答案 0 :(得分:2)

您需要将MovieSerializer添加为MoviesCategoriesSerializer字段:

class MoviesCategoriesSerializer(serializers.ModelSerializer):
    movies = MovieSerializer(many=True, read_only=True)
    class Meta:
        model = MoviesCategories
        fields = ('name', 'movies')

详见here