Mislav
Mislav

Reputation: 668

Django Rest Framework serializing queryset fetchedn with value_list

I'm trying to query a specific column from my table. I've tried doing it with this

team_lenDeserialized = RolesInTeam.objects.values_list('user_id', flat=True).filter(academic_year_id=9).filter(deleted=0)
team_lenDict = RolesInTeamSerializer(team_lenDeserialized, many=True)
team_len = orderedDictToJSON(team_lenDict.data)

After that I run it through a function that converts it to JSON

def orderedDictToJSON(orderedDict):
    return json.loads(json.dumps(orderedDict))

then I go and manipulate it further. However if I try to serialize and convert the team_lenDeserialized I get an error that states

AttributeError: Got AttributeError when attempting to get a value for field `user_id` on 
serializer RolesInTeamSerializer`.
The serializer field might be named incorrectly and not match any 
attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'user_id'.

This is my model for that table

class RolesInTeam(models.Model):
    user_id = models.IntegerField()
    team_id = models.IntegerField()
    role_id = models.IntegerField()
    deleted = models.IntegerField()
    academic_year_id = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'roles_in_team'

and my serializer

class RolesInTeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = RolesInTeam
        fields = ['id', 'user_id', 'team_id', 'role_id', 'deleted', 'academic_year_id']

I have no clue what's happening or why it's not working.

Upvotes: 1

Views: 1332

Answers (2)

YosSaL
YosSaL

Reputation: 1082

When using flat=True, just do not use a serializer, or at least edit it to fit your new data structure, this query will return only a list of user_ids and you can simply turn it to json:

team_lenDeserialized = RolesInTeam.objects.values_list('user_id', flat=True).filter(academic_year_id=9).filter(deleted=0)
team_len = orderedDictToJSON(list(team_lenDeserialized))

Upvotes: 0

HuLu ViCa
HuLu ViCa

Reputation: 5454

You can only serialize models instances with a ModelSerializer, and values_list() returns a queryset of tuples, so when you try to use the serializer over the queryset, you get the error.

If you make a regular query (team_lenDeserialized = RolesInTeam.objects.filter(academic_year_id=9).filter(deleted=0)), you would be able to serialize team_lenDeserialized.

Upvotes: 0

Related Questions