I have implemented the follow model to capture the structure of a classical piece of music. I'm using the MPTT to implement movements, opera acts and arias.
model.py:
TreeForeignKey(Work, blank=True, null=True, db_index=True, on_delete=models.PROTECT).contribute_to_class(Work, 'parent')
mptt.register(Work, order_insertion_by=['id'])
class Work(models.Model):
attributed_to = models.NullBooleanField()
name = models.CharField(max_length=400, null=True, blank=True)
lang = models.CharField(max_length=2, null=True, blank=True)
name_original = models.CharField(max_length=200, null=True, blank=True)
lang_original = models.CharField(max_length=2, null=True, blank=True)
name_common = models.CharField(max_length=200, null=True, blank=True)
name_common_orig = models.CharField(max_length=200, null=True, blank=True)
dedicated_to = models.CharField(max_length=200, null=True, blank=True)
pic = models.ImageField(upload_to = 'pic_folder/', default = '/pic_folder/None/no-img.jpg')
piece_type = models.CharField(max_length=100, null=True, blank=True)
category = models.CharField(max_length=100, null=True, blank=True)
date_start = models.CharField(max_length=100, null=True, blank=True)
date_start_gran = models.CharField(max_length=5, choices=DATE_TYPES, default='Year')
date_signature = models.CharField(max_length=100, null=True, blank=True)
date_signature_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year')
around = models.BooleanField(null=True)
date_published = models.CharField(max_length=100, null=True, blank=True)
date_published_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year')
desc = models.TextField(max_length=8000, null=True, blank=True)
order = models.CharField(max_length=100, null=True, blank=True)
class Work_Music(Work):
composer = models.ForeignKey(Composer, verbose_name=_('composer'), null=True, blank=True, on_delete=models.PROTECT)
key = models.CharField(max_length=10, null=True, blank=True)
tonality = models.CharField(max_length=20, null=True, blank=True)
Here is the view.py:
class ComposerOverviewView(TemplateView):
template_name = 'composers/overview/catalogue.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
opus = Work_Music.objects.filter(composer=self.kwargs['pk'], level=0)
context.update({
'composer': Composer.objects.get(pk=self.kwargs['pk']),
'opus': opus,
})
return context
When I try to run a query for all of the works for a composer (in the DB there are a total of 264 works), the queryset take almost 6 secs to run. I was wondering if anyone knows how to improve my code to increase the performance. There seems to be some with the delay_mptt_updates() method. But I'm not sure where it would go in my code.
I read in another article that MPTT sometimes does run slow. If I can increase the performance, what are some other alternatives?