计算 django rest 框架中的电影数量

Count the no of movies in django rest framework

我想统计api中演员的电影数量。我试过这个但没有用 models.py

class Actor(models.Model):
    actors = models.CharField(max_length=100)

class Genre(models.Model):
    genre = models.CharField(max_length=100)
    
class Movie(models.Model):
    name = models.CharField(max_length=100)
    actors = models.ManyToManyField(Actor, related_name="actor_movies")
    genre = models.ManyToManyField(Genre,related_name="genre_movies")

serializers.py

class ActorSerializer(serializers.HyperlinkedModelSerializer):
    actor_movies = serializers.RelatedField(source='actor.movies', read_only = True)
    class Meta:
        model = Actor
        fields = ['id','actors','actor_movies']

class GenreSerializer(serializers.HyperlinkedModelSerializer):
    genre_movies = serializers.RelatedField(source='genre.names', read_only = True)
    class Meta:
        model = Genre
        fields = ['id','genre','genre_movies']

class MovieSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Movie
        fields = ['url','name','actors','genre']

我得到这样的输出

[
    {
        "id": 1,
        "genre": "Ajith"
    },
    {
        "id": 2,
        "genre": "Vijay"
    }
]

在实际输出中我还需要他工作的电影总数。

您可以使用 SerializerMethodField:

class ActorSerializer(serializers.HyperlinkedModelSerializer):
    count_actor_movies= serializers.SerializerMethodField()

    def get_count_actor_movies(self, instance):
        return instance.actor_movies.count()

    class Meta:
        model = Actor
        fields = ['id','actors','count_actor_movies']

更多细节,官方文档是here