Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Efficient Version query on a subset of tracked objects #978

Open
airguru opened this issue Dec 22, 2024 · 0 comments
Open

Efficient Version query on a subset of tracked objects #978

airguru opened this issue Dec 22, 2024 · 0 comments

Comments

@airguru
Copy link

airguru commented Dec 22, 2024

Hello,

I have encountered a use case, where I need to query for all changes in some subset of tracked objects. Consider this example:

content_type = ContentType.objects.get_for_model(Model)
relevant_object_ids = Model.objects.filter( <some_condition> ).annotate(pk_str=Cast('pk', CharField())).values('pk_str')

relevant_versions = Version.objects.filter(content_type=content_type, object_id__in=Subquery(relevant_object_ids))

My Versions table is fairly big and contains over 8-10M versions for this content_type. This query is very slow, unless an database index for (content_type, object_id) is added.

Do you think adding such an index might be considered as a feature?

Actually, my exact use case is a level more complicated. I need to produce an audit report, where I list all objects that have been changed. Then go through all the changes and filter out only the relevant ones.

My approximate real code looks like this:

deals_in_range = Deal.objects.filter(date__gte=start_date, date__lt=end_date, company=company).exclude(counterparty=company).annotate(pk_str=Cast('pk', CharField())).values('pk_str')

content_type = ContentType.objects.get_for_model(Deal)

relevant_object_ids = Version.objects.filter(
        content_type=content_type, object_id__in=Subquery(deals_in_month),
    ).values('object_id').annotate(
        version_count=Count('object_id')
    ).filter(version_count__gt=1).values('object_id')

relevant_versions = Version.objects.filter(content_type=content_type, object_id__in=Subquery(relevant_object_ids))

I wonder if there is a better approach to this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant