@@ -0,0 +1,18 @@ +# Generated by Django 5.0.11 on 2025-11-16 16:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + ('msgs', '0009_delete_messageerror'), + ] + + operations = [ + migrations.AddIndex( + model_name='message', + index=models.Index(fields=['object_id', '-created_at'], name='msgs_messag_object__09670f_idx'), + ), + ] @@ -72,4 +72,7 @@ class Message(models.Model): verbose_name = 'Сообщение' verbose_name_plural = 'Сообщения' ordering = ['-created_at'] - indexes = [models.Index(fields=['content_type', 'object_id'])] + indexes = [ + models.Index(fields=['content_type', 'object_id']), + models.Index(fields=['object_id', '-created_at']), + ] @@ -3,18 +3,38 @@ from uuid import uuid4 from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericRelation from django.db import models -from django.db.models import QuerySet +from django.db.models import F, Max, OuterRef, QuerySet, Subquery from ml_model.models import NeuronModel from .message import Message +class BaseManager(models.Manager): + def get_queryset(self): + queryset = super().get_queryset() + + last_messages_query = ( + Message.objects.filter( + content_type__app_label=self.model._meta.app_label, + content_type__model=self.model._meta.model_name, + ) + .annotate(last_created=Max('created_at')) + .filter(object_id=OuterRef('pk')) + .values('object_id', 'last_created') + ) + + return queryset.annotate(last_message_created=Subquery(last_messages_query)).order_by( + F('last_message_created').desc(nulls_last=True) + ) + + class BaseStore(models.Model): """ Abstract schema of base store. Store is a storage for store messages and create relations with user(s) and models """ + objects = BaseManager() uid = models.UUIDField( verbose_name='Идентификатор', primary_key=True, @@ -0,0 +1,17 @@ +# Generated by Django 5.0.11 on 2025-11-16 16:40 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('chats', '0003_alter_chat_options_alter_chat_created_at_and_more'), + ] + + operations = [ + migrations.AlterModelOptions( + name='chat', + options={'verbose_name': 'Chat', 'verbose_name_plural': 'Chats'}, + ), + ] @@ -19,4 +19,3 @@ class Chat(MultipleStore): class Meta: verbose_name = _('Chat') verbose_name_plural = _('Chats') - ordering = ['-created_at'] @@ -33,7 +33,7 @@ services: condition: service_started migrator: - restart: on-failure:1 + restart: on-failure:3 container_name: migrator volumes: - .:/code