【发布时间】:2016-10-27 18:56:51
【问题描述】:
我想构建一个像Quora 或Medium 这样的网络应用程序,用户可以在其中关注用户或某些主题。
例如:userA 正在关注(userB、userC、tag-Health、tag-Finance)。
这些是模型:
class Relationship(models.Model):
user = AutoOneToOneField('auth.user')
follows_user = models.ManyToManyField('Relationship', related_name='followed_by')
follows_tag = models.ManyToManyField(Tag)
class Activity(models.Model):
actor_type = models.ForeignKey(ContentType, related_name='actor_type_activities')
actor_id = models.PositiveIntegerField()
actor = GenericForeignKey('actor_type', 'actor_id')
verb = models.CharField(max_length=10)
target_type = models.ForeignKey(ContentType, related_name='target_type_activities')
target_id = models.PositiveIntegerField()
target = GenericForeignKey('target_type', 'target_id')
tags = models.ManyToManyField(Tag)
现在,这将给出以下列表:
following_user = userA.relationship.follows_user.all()
following_user
[<Relationship: userB>, <Relationship: userC>]
following_tag = userA.relationship.follows_tag.all()
following_tag
[<Tag: tag-job>, <Tag: tag-finance>]
过滤我试过这样:
Activity.objects.filter(Q(actor__in=following_user) | Q(tags__in=following_tag))
但是由于 actor 是 GenericForeignKey 我收到了一个错误:
FieldError:字段'actor'不会生成自动反向关系,因此不能用于反向查询。如果是 GenericForeignKey,请考虑添加 GenericRelation。
如何使用用户列表和用户关注的标签列表过滤将是唯一的活动?具体来说,我将如何使用对象列表过滤 GenericForeignKey 以获取以下用户的活动。
【问题讨论】:
-
OT:我成功地将这个包(在一个非平凡的 webapp 上的生产中)用于您描述的用例:github.com/bitmazk/django-object-events。
-
嗨@Aamu,请告诉我,如果这样做可以让您毫无问题地获得结果。
Activity.objects.filter(actor__in=following_user)有效。? -
@simonecittadini 谢谢。我一定会检查一下。
-
@Trying2Learn 不,
Activity.objects.filter(actor__in=following_user)是引发错误的原因。