如何在Django中从ManyToManyField中获取对象的数量?

li9yvcax  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(104)

我有用户和事件模型,

class User(AbstractUser):
    bio = models.CharField(max_length=255, blank=False, default='')

class Event(models.Model):
    name    = models.CharField(max_length=50)
    user    = models.ManyToManyField("User", related_name='event_player')

我想获取事件中注册的用户数,我尝试了以下方法:
尝试1

class EventSerializer(serializers.ModelSerializer):

    players_count = serializers.IntegerField(
        source='user_set.count', 
        read_only=True
    )

    class Meta:
        model = Event
        fields = ('id', 'name','players_count')

试试2

class EventSerializer(serializers.ModelSerializer):

    players_count = serializers.SerializerMethodField()

    class Meta:
        model = Event
        fields = ('id', 'name','players_count')

    def get_players_count(self, obj):
        return obj.user_set.all().count()

试试3

class EventSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        return {'id': instance.pk, 'players_count': instance.user__count}
        
    class Meta:
        model = Event
        fields = ('id', 'name','players_count')

但是它们都没有意义,我如何获得嵌套的ManyToMany用户的总数。我是新来的DRF请帮助我解决这个问题。

a64a0gku

a64a0gku1#

Try 2应该可以在没有_set的情况下工作。有关详细信息,请参阅Django ManyToMany Docs

class EventSerializer(serializers.ModelSerializer):

    players_count = serializers.SerializerMethodField()

    class Meta:
        model = Event
        fields = ('id', 'name','players_count')

    def get_players_count(self, obj):
        return obj.user.all().count()

相关问题