0

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.

MPagan
  • 213
  • 1
  • 3
  • 13
  • 1
    Hi, please also include what you code tried, along with error message. This can help to solve your question quickly. – Ansuman Apr 26 '20 at 01:14

1 Answers1

1

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?

minglyu
  • 2,958
  • 2
  • 13
  • 32
  • Oh ok thanks for the response. Related query makes it easier to run the query. Question though, if i were to do a filter on ProtocolDataSource, but for data_sources objects what would the filter look like? Or even on users objects in Protocol. Still confused on the through portion and how it affects the filter. – MPagan Apr 26 '20 at 16:21