2

Filtering on Django GenericRelations has been implemented 4 years ago via https://code.djangoproject.com/ticket/22207 and supports now to filter from the related model:

class Issue(models.Model):
    project_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=False, null=True)
    project_id = models.PositiveIntegerField(blank=False, null=True)
    project = GenericForeignKey('project_content_type', 'project_id')

class GitlabProject(models.Model):
    issues = GenericRelation(
        Issue,
        related_query_name='generic_project',
        content_type_field='project_content_type',
        object_id_field='project_id',
)

and then:

issues = queryset.filter(generic_project__offers__members__in=[request.user])

We cannot use just project__offers_members - it would fail, as Django does not reversely resolve Generic Foreign Keys.

However what happens if we have another project model with the same related_query_name?

class JiraProject(models.Model):
    issues = GenericRelation(
        Issue,
        related_query_name='generic_project',
        content_type_field='project_content_type',
        object_id_field='project_id',
)

I have tried setting the GenericRelation with the same related_query_name on all the different project models (i.e. Gitlab Project, Jira Project, etc.). However that results in Django picking up only the 'first' project model. The generic relation to all subsequent project models are ignored and as a result, issues that have instances set that do not belong to the 'first' project model are ignored and not part of the queryset.

I think Django should either support this or issue a warning or error (possibly when executing the makemigrations command), when multiple GenericRelations have the same related_query_name value set.

How can one filter efficiently across issues that have their project attribute set to instances of different models?

Mario
  • 2,619
  • 1
  • 24
  • 22

0 Answers0