Code: Select all
from django.db.backends.signals import connection_created
from django.db.backends.postgresql.base import DatabaseWrapper
from django.dispatch import receiver
from notification_type_singleton import NotificationTypeSingleton
from models import NotificationType
@receiver(connection_created, sender=DatabaseWrapper)
def create_or_update_notification_type(sender, **kwargs):
exiting_ids = []
for _, notification_type in (
NotificationTypeSingleton._data.items()
):
notification, _ = NotificationType.objects.update_or_create(
name=notification_type.name,
defaults={
'description': notification_type.description,
'is_active': True,
},
)
exiting_ids.append(notification.id)
# Deactivate all notifications in the database that are not used
NotificationType.objects.exclude(id__in=exiting_ids).update(is_active=False)
# Update the registry with the created events
NotificationTypeSingleton._registry = {
notification.name: notification
for notification in NotificationType.objects.filter(is_active=True)
}
Wenn das Signal verwendet wird. Um zu vermeiden, dass Initialisierungsabfragen an der Produktionsdatenbank ausgeführt werden, wenn sie nicht benötigt wird (z. B. beim Ausführen von Tests). Django konnte keine Verbindung zur "Postgres" -Datenbank erstellen und verwendet stattdessen die erste Postgresql -Datenbank. Gleichzeitig sollte gemäß den Dokumenten das Signal Connection_Created < /code> für < /p>
... Jede Postverbindungsbefehle zum SQL -Backend verwendet werden. Hat jemand anderes ähnliche Probleme mit dem Testen gehabt?