Answer the question
In order to leave comments, you need to log in
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 = 'Чаты'
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
c = Contact.objects.filter(id=1).raw('SELECT *, id AS chat_id FROM chat_chat WHERE participants=1 AND participants=2')
OperationalError: no such column: participants
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question