'to return True when the post has a like from the creator of the post
to return True when the post has a like from the creator of the post how to make such an analog on django
user = {
'id': 121
}
likes = [{
'userInfo': {
'id': 121
}
}]
hasSelfLike = any(like['userInfo']['id'] == user['id'] for like in likes)
print(hasSelfLike)
models.py
class Task(models.Model):
user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo')
title = models.CharField(max_length=100)
text = models.TextField(max_length=10000)
def get_hasSelfLike(self):
return self.likes.values_list('userInfo_id', 'userInfo__id') #returns always True
class Like(models.Model):
task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='likes', name='taskId')
user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo')
Solution 1:[1]
You can filter the Tasks to return Tasks with the user as like through an F object [Django-doc] to refer to a field, so:
from django.db.models import F
Task.objects.filter(
likes__user_info=F('user_info')
)
or for a Task, you can check in a Task with:
def has_self_like(self):
return self.user_info_id in self.likes.values_list('user_info_id', flat=True)
or through an exists():
def has_self_like(self):
return self.likes.filter(user_info_id=self.user_info_id).exists()
Note: Normally one does not add a suffix
_idto aForeignKeyfield, since Django will automatically add a "twin" field with an_idsuffix. Therefore it should betask_id, instead of.task
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
