我想在我的应用程序中使用 GenericRelation 来实现“喜欢”功能。
我已经有这些模型:
class Activity(models.Model):
LIKE = 'L'
ACTIVITY_TYPES = (
(LIKE, 'Like'),
)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES)
date = models.DateTimeField(auto_now_add=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
def __str__(self):
return str(self.user)
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = RichTextUploadingField()
likes = GenericRelation(Activity, related_query_name='posts')
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
我的views.py文件我有这样的行:
activity = Activity.objects.get(content_type=ContentType.objects.get_for_model(obj), object_id=obj.id, user=request.user)
我的问题是,我如何才能获得该用户已经喜欢这篇文章的信息?