R
R
reqww2020-09-09 19:33:02
Django
reqww, 2020-09-09 19:33:02

How to write raw sql correctly?

There is a chat model:

class Chat(models.Model):
    participants = models.ManyToManyField(Contact, related_name='chats')
    messages = models.ManyToManyField(Message, blank=True)

    def __str__(self):
        return f'{self.pk}'

    class Meta:
        verbose_name = 'Чат'
        verbose_name_plural = 'Чаты'


and there is a user model:
class Contact(AbstractBaseUser, PermissionsMixin):
    '''Кастомная модель пользователя'''
    email = models.EmailField(verbose_name='email', max_length = 60, unique = True)
    slug = models.SlugField(default='')
    first_name = models.CharField(max_length=30, default = '')
    last_name = models.CharField(max_length=30, default = '')
    phone_number = models.CharField(max_length=11)
    date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add = True)
    last_login = models.DateTimeField(verbose_name='last login', auto_now = True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    avatar = models.ImageField(upload_to='user_avatars/%Y/%m/%d', blank=True)
    is_active = models.BooleanField(default=False)
    status = models.CharField(max_length=100, default='', blank=True)
    friends = models.ManyToManyField('self', blank=True)
    

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_number', 'slug']

    objects = ContactManager()

    def __str__(self):
        return self.email

    def get_url(self):
        try:
            return self.avatar.url
        except ValueError:
            return None


I'm trying to extract from this table the chat in which there are certain participants
. In this case, these are participants with id 1 and 2, but later these will be certain participants.
I tried to write something like this:
c = Contact.objects.filter(id=1).raw('SELECT *, id AS chat_id FROM chat_chat WHERE participants=1 AND participants=2')

But I get an error:
OperationalError: no such column: participants

What is my mistake?
And how would you write it to make it work?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-09-09
@bacon

1. ManyToManyField is implemented through an intermediate table, there will be no participants explicitly there, deal with it, just look through dbshell
2. raw most likely can no longer be applied to a QuerySet (perhaps through some RawSQL, but definitely not)
3. Query simple , why is raw here at all?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question