Django - Annotate post query set data with if current user has "liked" the post
So I have this model
model.py
class Post(models.Model):
uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False)
created = models.DateTimeField('Created at', auto_now_add=True)
updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True)
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post_creator")
body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)])
class LikePost(AbstractSimpleModel):
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="like_post")
post = models.ForeignKey(Post, on_delete=models.CASCADE)
class User(AbstractDatesModel):
uuid = models.UUIDField(primary_key=True)
username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[
MinLengthValidator(USERNAME_MIN_LEN)])
created = models.DateTimeField('Created at', auto_now_add=True)
updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True)
Then I also have this annotator for returning a bunch of data outside of the Post table
annotator.py
def query_to_full_post_data_serializer(post_query_set: QuerySet):
query_set_annotated = post_query_set.annotate(
creator_username=F('creator__username'),
reply_count=Count('postreply', distinct=True),
like_count=Count('likepost', distinct=True)
).prefetch_related(
Prefetch('photo', Photo.objects.order_by('-created')),
Prefetch('video', Video.objects.order_by('-created'))
)
return FullPostDataSerializer(query_set_annotated, many=True)
I'd like to return a field called "user_liked", which returns a boolean for each post in a query set that is True
if the current logged in user has liked it. When the request comes in I get the current user making the request so I can get their uuid
. I'd like to use that uuid to check if the user has liked a post in the query set. How do I check if the current logged in user has liked a Post
object in a query set Django?
Sorry for my previous wrong answer.
So I'm quite rusty in the Django ORM so that query might not have best optimisation. Here is what I have come up with
Post.objects.all().annotate(liked_by_user=Q(likepost__creator=user))
The issue being that it will add duplicates for each reverse relationship it finds. That's why you should not use that and use a many to many.
For example, with a many to many, it would be as simple as
class User2(models.Model):
_id = models.BigAutoField(primary_key=True)
class Post2(models.Model):
_id = models.BigAutoField(primary_key=True)
creators = models.ManyToManyField(User2)
and now you only need
Post2.object.all().annotate(liked_by_user=Q(creator__in=[user]))
which is way better.