NakedPython
NakedPython

Reputation: 930

Django: Filter for all actions related to the ForeignKey Object

I've got a Model called User which looks like this:

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:

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.

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? Is that even possible? Or would I have to create a custom function in my Club Model?

Appreciate all answers! :)

Upvotes: 0

Views: 43

Answers (1)

HenryM
HenryM

Reputation: 5793

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.

Upvotes: 1

Related Questions