我是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
返回第一类
答案 0 :(得分:2)
您需要将MovieSerializer
添加为MoviesCategoriesSerializer
字段:
class MoviesCategoriesSerializer(serializers.ModelSerializer):
movies = MovieSerializer(many=True, read_only=True)
class Meta:
model = MoviesCategories
fields = ('name', 'movies')
详见here。