[英]Django: Filter for all actions related to the ForeignKey Object
I've got a Model called User
which looks like this: 我有一个名为
User
的模型,看起来像这样:
class User(AbstractBaseUser, PermissionsMixin):
...some fields...
club = models.ForeignKey('schedule.Club', on_delete=models.CASCADE, null=True, blank=True)
And for my APP I'm creating History Items, which I want to let my users see if they're logged in. So far I only show History Items that are related to them: 对于我的APP,我正在创建历史记录项目,我想让我的用户查看他们是否已登录。到目前为止,我只显示与他们相关的历史记录项目:
class HistoryItems(ListView):
model = HistoryItem
template_name = 'history/history_items_table.html'
context_object_name = 'history_items'
def get_context_data(self, **kwargs):
history_item_query = HistoryItem.objects.filter(Q(changed_by=self.request.user) | Q(object_id=self.request.user.pk)).select_related('changed_by', 'content_type')
return {
'filter_history_form': HistoryFilterForm(),
'history_items': history_items,
}
So if they get changed or change something themselves they can see that. 因此,如果他们被更改或自己更改了某些内容,他们可以看到。 But now I also want to show them all changes that were done to the Club that they have chosen.
但是现在我也想向他们展示他们选择的俱乐部所做的所有更改。 So for example if "User1" has "Club1" as ForeignKey, and I change the name of Club1 to Club2 I want the User1 to see that in the history items.
因此,例如,如果“ User1”具有“ Club1”作为ForeignKey,并且我将Club1的名称更改为Club2,我希望User1在历史记录项中看到它。
My History Model looks like this: 我的历史记录模型如下所示:
class HistoryItem(models.Model):
changed_at = models.DateTimeField('Changed At', auto_now_add=True)
description = models.TextField('Description', max_length=300)
changed_by = models.ForeignKey('users.User', on_delete=models.SET_NULL, related_name="history_items", null=True)
action = models.CharField('Action', max_length=50, choices=ACTION_CHOICES)
difference = JSONField('Differences', encoder=DjangoJSONEncoder, null=True, blank=True)
# Generic object foreign key
object_id = models.IntegerField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
content_object = GenericForeignKey('content_type', 'object_id')
How would I have to "rebuild" my history_item_query
to achieve that? 我必须如何“重建”
history_item_query
才能实现? Is that even possible? 那有可能吗? Or would I have to create a custom function in my Club Model?
还是我必须在俱乐部模型中创建自定义功能?
Appreciate all answers! 感谢所有答案! :)
:)
Can't you simply do: 您不能简单地做:
history_item_query = HistoryItem.objects.filter(Q(changed_by=self.request.user) | Q(object_id=self.request.user.pk) | Q(content_object=self.request.user.club)).select_related('changed_by', 'content_type')
And if that doesn't work, get the content type & object for the user's club and filter on that. 如果那行不通,请获取用户俱乐部的内容类型和对象,然后对此进行过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.