当帖子有来自帖子创建者的赞时返回True如何在django 上制作这样的模拟
user = {
'id': 121
}
likes = [{
'userInfo': {
'id': 121
}
}]
hasSelfLike = any(like['userInfo']['id'] == user['id'] for like in likes)
print(hasSelfLike)
型号.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')
您可以通过引用字段的F
对象[Django-doc]来过滤Task
s以与用户一起返回Task
s,因此:
from django.db.models import F
Task.objects.filter(
likes__user_info=F('user_info')
)
或者对于Task
,您可以使用办理Task
def has_self_like(self):
returnself.user_info_idin self.likes.values_list('user_info_id', flat=True)
或通过exists()
:
def has_self_like(self):
return self.likes.filter(user_info_id=self.user_info_id).exists()
注意:通常不会在
ForeignKey
字段中添加后缀_id
,因为Django将自动添加一个";双";带有_id
后缀的字段。因此,它应该是task_id
而不是。task