'how to get data from database using django channels?

I'm trying to practice WebSocket implementation using django channels by querying the database and printing the data but I am unsuccessful.

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from .models import Chart
from chart.api.serializers import ChartSerializer


class ChartConsumer(AsyncWebsocketConsumer):
    def get_chart(self):
        return database_sync_to_async(Chart.objects.all)()

    async def connect(self):

        data = self.get_chart()
        print(data) # <-------- I want to get this data
        # for i in data:
        #     chart_data = ChartSerializer(i).data
        #     await self.send(json.dumps({'number': chart_data.number}))
        #     print(chart_data)
        await self.accept()

    async def disconnect(self, code):
        pass

Output

enter image description here



Solution 1:[1]

You need the database_sync_to_async to be called in the connect method. Like so:

class ChartConsumer(AsyncWebsocketConsumer):

    def get_chart(self):
        return Chart.objects.all()

    async def connect(self):
        data = await database_sync_to_async(self.get_chart)()
        print(data)
        # for i in data:
        #     chart_data = ChartSerializer(i).data
        #     await self.send(json.dumps({'number': chart_data.number}))
        #     print(chart_data)
        await self.accept()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lewis