title: Integrate Paho MQTT with Django
body: <p>I am doing a project which use Django and MQTT. There is a situation that I want to re-subscribe all topics relating to models in database when my Django web server reconnect to the broker after disconnecting for some reason. I have the model Room as below:</p>
  
  <pre><code>class Room(models.Model):
      building    = models.ForeignKey(Building, on_delete= models.CASCADE)
      number      = models.PositiveIntegerField()
      available   = models.BooleanField(default=True)
      power       = models.BooleanField(default=False)
  
  class Meta:
      ordering = ['building', 'number']
      unique_together = ['building', 'number']
  
  def __str__(self):
      return f"{self.building.bid}/{self.number}"
  
  def get_mqtt_topic(self):
      return f"{self.building.bid}/{self.number}"
  </code></pre>
  
  <p>The method get_mqtt_topic() will return the MQTT topic associated to the room. MQTT client code mqtt/client.py:</p>
  
  <pre><code>import paho.mqtt.client as mqtt
  from .tasks import *
  from .models import Room
  def on_connect(client, userdata, flags, rc):
     print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc))
     room_mqtt = [(room.get_mqtt_topic(), 1) for room in Room.objects.all()]
     client.subscribe(room_mqtt)
  
  client = mqtt.Client()
  client.on_connect = on_connect
  client.on_message = on_message
  </code></pre>
  
  <p>Because I put the code below in <strong>init</strong>.py to run mqtt client in a different thread from the django app.</p>
  
  <pre><code>from mqtt.client import client
  
  client.loop_start()
  </code></pre>
  
  <p>so I got this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.</p>