我有用户和事件模型,
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请帮助我解决这个问题。
1条答案
按热度按时间a64a0gku1#
Try 2应该可以在没有
_set
的情况下工作。有关详细信息,请参阅Django ManyToMany Docs