0

I have two models:

Base_Activity:

topics = models.ManyToManyField(Topic)
... some others

User_Activity:

user = models.ForeignKey(settings.AUTH_USER_MODEL)
activity = models.ForeignKey(Base_Activity)
is_archived = models.BooleanField(default=False)

Now I want to query Base_activity to select all rows with topic X and exclude any rows that have a matching row in User_Activity for user=*current_user* and is_archived=True.


I have read the Django docs on how to follow relationships backward, since I query Base_Activity, but need information from User_Activity which has a ForeignKey to the former. However, even testing this method in the Django console doesn't work:

a = Base_Activity.objects.filter(topics__slug = topic)
a.user_activity_set.all()
AttributeError: 'InheritanceQuerySet' object has no attribute 'user_activity_set'

Question: What is the best way to do my query? If this is indeed by following the ForeignKey backwards, then what am I doing wrong?

4

2 回答 2

0

我不确定这会解决你的问题,但无论如何请不要在 Python 的类名中使用下划线

于 2013-10-14T17:19:31.063 回答
0
a = Base_Activity.objects.filter(topics__slug = topic)

这将返回一个 QuerySet 实例,而不是模型实例。您应该遍历它或只从列表中获取一个:

activities = Base_Activity.objects.filter(topics__slug=topic)
activities[0].user_activity_set.all()

在您的情况下,您可以在一个查询中完成全部工作:

activities = Base_Activity.objects.filter(topics__slug=topic).exclude(user_activity__user=user, user_activity__is_archived=True)
于 2013-10-14T17:22:32.690 回答