Home > Back-end >  How to convert a List of objects to a queryset in Django
How to convert a List of objects to a queryset in Django

Time:04-21

I've used chain from itertools to join more than a single queryset into 1 list. but after that when I try to use the generated list. it fails with the error :

AttributeError: 'list' object has no attribute 'all'

Here is how I do this :

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        parent = self.get_parent_object_from_request(request)
        home_team_object = parent.home_team
        away_team_object = parent.away_team
        if db_field.name == "team":
            kwargs["queryset"] = Team.objects.filter(
                Q(away_team_team=parent) | Q(home_team_team=parent))
        if db_field.name == "player":
            parent = self.get_parent_object_from_request(request)
            print(parent)
            away_team_players = away_team_object.players.all()
            home_team_players = home_team_object.players.all()
            cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id))
            result_list = list(chain(away_team_players, home_team_players, cap_objects))
            print(result_list)
            kwargs["queryset"] = result_list
        if db_field.name == "assistant":
            parent = self.get_parent_object_from_request(request)
            print(parent)
            away_team_players = away_team_object.players.all()
            home_team_players = home_team_object.players.all()
            cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id))
            result_list = list(chain(away_team_players, home_team_players, cap_objects))
            print(result_list)
            kwargs["queryset"] =result_list
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

Here is where I tried to call 3 different querysets from the same Model than tried to merge them into 1 query set :

            away_team_players = away_team_object.players.all()
            home_team_players = home_team_object.players.all()
            cap_objects = PlayerProfile.objects.filter(Q(id=home_team_object.cap.id) | Q(id=away_team_object.cap.id))
            result_list = list(chain(away_team_players, home_team_players, cap_objects))

CodePudding user response:

We can not convert a data list back to a query. Because query object never holds data; it just refers to the database.

See the example

CodePudding user response:

Solved it by changing

result_list = list(chain(away_team_players, home_team_players, cap_objects))

To be

result_list = home_team_players | away_team_players | cap_objects
  • Related