djangodjango-modelsdjango-rest-frameworkdjango-serializerpython-django-storages

BooleanField in ModelSerializer


I want to display the content of Trader class through an API call. But I don't know where am I wrong.

models.py

class Trader(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="trader")
    bot_status = models.BooleanField(blank=False, default=False)
    active_group = models.ManyToManyField(Entry, blank=True, related_name="active_group")

    def __str__(self):
        return f'{self.user.username}'

    def __repr__(self):
        return f'Trader=(bot_status={self.bot_status}, active_group={self.active_group})'

serializers.py

class BotStatusSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source = 'user.username')

    class Meta:
        model = Trader
        read_only_fields = ('bot_status', )

views.py

class BotStatusView(viewsets.ModelViewSet):
    serializer_class = BotStatusSerializer
    
    def get_queryset(self):
        return self.request.user.trader.bot_status

When I make the request I get the following Error.

Error:

    return [
TypeError: 'bool' object is not iterable

Solution

  • You are returning bot_status, a boolean, from get_queryset, which needs to return a QuerySet.

    def get_queryset(self):
        return Trader.objects.filter(trader=self.request.user)