MPagan
MPagan

Reputation: 253

How to filter for a ManytoManyField with through in Django?

Trying to filter through all protocol data sources with their specific datasources in Protocol.

Tried to use this: ProtocolDataSource.objects.filter(protocol__data_sources=..., protocol__data_sources=...) but obviously this comes up with an error. The dots are the name of the data source.

Upvotes: 0

Views: 194

Answers (1)

minglyu
minglyu

Reputation: 3337

To make your related_query_name more predictable, I suggest to add parameter related_query_name in your ManytoManyField

class Protocol(BaseWithImmutableKey):

    name = models.CharField(
        max_length=200, unique=True, verbose_name='Protocol Name')

    # add related_query_name
    data_sources = models.ManyToManyField(
        DataSource, through='ProtocolDataSource', related_query_name='protocols')


# now you can reference reversely using protocols
DataSource.objects.filter(protocols__name=...)

You can read more here what is related_name and related_query_name in django?

Upvotes: 1

Related Questions