Hi I am trying to send all instances of an Model through a websocket, following is my code
#consumer.py
class ChangeBoatConsumer(AsyncWebsocketConsumer):
@database_sync_to_async
def all_boats(self):
boats = Boat.objects.all()
return boats
async def connect(self):
await self.channel_layer.group_add('all_boats', self.channel_name)
await self.accept()
boats = await self.all_boats()
boats_serializer = BoatSerializer(boats, many=True)
boats_data = boats_serializer.data
await self.send(json.dumps({
"boat": boats_data,
}))
#models.py
class Boat(models.Model):
name = models.CharField(max_length=200)
type = models.CharField(max_length=200)
captain = models.OneToOneField(Captain,on_delete=models.CASCADE, null=True, blank=True)
class Captain(models.Model):
name = models.OneToOneField(Person, on_delete=models.CASCADE)
date_of_birth = models.DateField(null=True, blank=True)
joined_date = models.DateField(null=True, blank=True)
#Serializer.py
class BoatSerializer(serializers.ModelSerializer):
captain = serializers.StringRelatedField()
class Meta:
model = Boat
fields = ['name','type', 'captain',]
class CaptainSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='name.username')
first_name = serializers.CharField(source='name.first_name')
last_name = serializers.CharField(source='name.last_name')
class Meta:
model = Captain
fields = ['name','date_of_birth', 'joined_date', ]
and when I visit the link of my consumer I get this message:
raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /ws/changeboat/
What am I doing wrong here, is there something I am missing?