I have two models that are linked via Many-To-Many field via third Through Model. The Through Model has some extra fields in it. I want to override the RelatedManager to produce some custom QuerySets that use the extra fields in the Through Model. The caveat is that my Through Model is created using a subclass/mixin that defines the extra fields. What I want to be able to do is get all the Gene objects related to the SampleBatch that have an active status of 1 in the SampleBatchGene instances linking the Many-to-Many fields:
In [1]: SampleBatch.objects.get(sample__lab_number="18_11998").genes.active()
Out[1]: <QuerySet [<Gene: BAP1>]>
This is what I have so far:
class SampleBatch(models.Model):
sample = models.ForeignKey(Sample, on_delete=models.CASCADE)
batch = models.ForeignKey(Batch, on_delete=models.CASCADE)
genes = models.ManyToManyField(
"Gene", through='SampleBatchGene', related_name='samplebatches',
blank=True, through_fields=('samplebatch', 'gene')
)
class Meta:
managed = True
db_table = 'sample_batch'
unique_together = (('sample', 'batch'),)
verbose_name_plural = "Sample batches"
def __str__(self):
return '{}-{}'.format(self.sample, self.batch)
class Gene(models.Model):
gene_id = models.BigAutoField(primary_key=True)
gene_name = models.CharField(unique=True, max_length=255, db_index=True)
hgnc_number = models.IntegerField(unique=True, db_index=True)
class Meta:
managed = True
db_table = 'gene'
def __str__(self):
return self.gene_name
class ActiveQuerySet(models.QuerySet):
def active(self):
return self.filter(active=1)
def inactive(self):
return self.filter(active=0)
class LinkMixin(models.Model):
ACTIVE_CHOICES = (
(0, 'Inactive'),
(1, 'Active')
)
activated = models.DateTimeField(default=timezone.now)
active = models.IntegerField(
choices=ACTIVE_CHOICES, default=1, db_index=True
)
created = models.DateTimeField(auto_now_add=True)
deactivated = models.DateTimeField(blank=True, null=True, default=None)
objects = models.Manager()
statuses = ActiveQuerySet.as_manager()
class Meta:
abstract = True
class SampleBatchGene(LinkMixin):
samplebatch = models.ForeignKey(SampleBatch, on_delete=models.CASCADE)
gene = models.ForeignKey(Gene, on_delete=models.PROTECT)
class Meta:
managed = True
db_table = 'sample_batch_gene'
unique_together = (('samplebatch', 'gene'), )
def __str__(self):
return '{}-{}'.format(self.samplebatch, self.gene)
Trying to use a custom reverse manager (as per the docs) gives the following error:
In [5]: SampleBatch.objects.get(sample__lab_number="18_11998").genes.all()
Out[5]: <QuerySet [<Gene: BAP1>]>
In [6]: SampleBatch.objects.get(sample__lab_number="18_11998").genes.filter(samplebatchgene__active=1)
Out[6]: <QuerySet [<Gene: BAP1>]>
In [7]: SampleBatch.objects.get(sample__lab_number="18_11998").genes(manager="statuses").active()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-d8d95f5854b4> in <module>
----> 1 SampleBatch.objects.get(sample__lab_number="18_11998").genes(manager="statuses").active()
~/.pyenv/versions/3.6.6/envs/varDB/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __call__(self, manager)
848
849 def __call__(self, *, manager):
--> 850 manager = getattr(self.model, manager)
851 manager_class = create_forward_many_to_many_manager(manager.__class__, rel, reverse)
852 return manager_class(instance=self.instance)
AttributeError: type object 'Gene' has no attribute 'statuses'
EDIT: Prompted by Willem Van Onsem: It's trying to use a custom manager from Gene
, but I've defined it against SampleBatchGene
. So I need work out how to specify the custom manager from the Through Model. I had hoped to make this work via the LinkMixin
so I wouldn't have to define the custom manager on both models at either end of the Many-To-Many
. I guess I could stick the custom manager on both SampleBatch
and Gene
and have it work, but I've got a lot of this type of relationship that uses the LinkMixin
as a Through Model so was hoping to avoid it somehow.