Answer the question
In order to leave comments, you need to log in
What is the correct way to write an annotation?
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)
compressed_avatar = models.ImageField(upload_to='compressed_user_avatars/%Y/%m/%d', blank=True)
small_avatar = models.ImageField(upload_to='small_user_avatars/%Y/%m/%d', blank=True)
is_active = models.BooleanField(default=False)
class Photo(models.Model):
'''Фотография'''
owner = models.ForeignKey(Page, related_name='photos', on_delete=models.CASCADE)
picture = models.ImageField(upload_to='picture/%Y/%m/%d')
compressed_picture = models.ImageField(upload_to='compressed_picture/%Y/%m/%d')
small_picture = models.ImageField(upload_to='small_picture/%Y/%m/%d')
likes = models.ManyToManyField(Like)
comments = models.ManyToManyField(Comment)
timestamp = models.DateTimeField(auto_now_add=True)
def get_queryset(self):
pk = int(self.kwargs['pk'])
queryset = Contact.objects.filter(id=pk).annotate(
is_friend=Count('my_page__friends', filter=Q(my_page__friends=self.request.user))
).annotate(
num_friends=Count('my_page__friends', distinct=True)
).annotate(
current_user=Count('slug', filter=Q(slug=self.request.user.slug))
).annotate(
is_sent=Exists(
AddRequest.objects.filter(
sender__id=self.request.user.id,
receiver__id=pk
)
)
).annotate(
is_sent_to_you=Exists(
AddRequest.objects.filter(
sender__id=pk,
receiver__id=self.request.user.id
)
)
).annotate(
chat_id=Avg('chats__id', filter=Q(chats__participants=self.request.user))
)
return queryset
queryset = queryset.annotate(
photo_id=Sum('my_page__photos__id', filter=Q(my_page__photos__picture=OuterRef('avatar')))
)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question