R
R
reqww2020-10-24 13:41:00
Django
reqww, 2020-10-24 13:41:00

What is the correct way to use OuterRef here?

There is a chat link model:

class ChatRef(models.Model):
    chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
    user = models.ForeignKey(Contact, on_delete=models.CASCADE, related_name='chat_refs')


There is a chat model:
class Chat(models.Model):
    participants = models.ManyToManyField(Contact, related_name='chats')
    messages = models.ManyToManyField(Message, blank=True)
    is_chat = models.BooleanField(default=True)
    creator = models.ForeignKey(Contact, null=True, on_delete=models.DO_NOTHING)
    name = models.CharField(max_length=30, null=True


There is also a view that displays friends. In order for everything to work properly, my front needs a flag to tell if the link to the chat exists. If it does not exist, the front will send a request and it will be created
def get_queryset(self):
        queryset = Contact.objects.exclude(id=self.request.user.id).annotate(
            chat_id=Sum('chats__id', filter=Q(chats__participants=self.request.user))
        ).annotate(
            exists_ref=Exists(Subquery(
                ChatRef.objects.filter(
                    user=self.request.user,
                    chat=Subquery(Chat.objects.get(
                        participants__in=[self.request.user, OuterRef(OuterRef('id'))],
                        is_chat=True
                    ))
                ))
            )
        )

        return queryset.filter(is_active=True)


But this code doesn't work and gives out
5f9404812efca551403538.png

How to make this work correctly?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question