Report building in Django

Viewed 103

I am trying to build a system which will enable my users to create their own reports based on the model of their choosing without me having to code them every time they need updating.

In order to do this, I've come up with the following models:-

from django.db import models
from django.contrib.contenttypes.models import ContentType


class ReportField(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    data_method = models.CharField(max_length=100)

    def get_value_for(self, object):
        return getattr(object, self.data_method)


class Report(models.Model):
    name = models.CharField(max_length=200)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    data_fields = models.ManyToManyField(ReportField)

The idea is that users can create a Report based on the model they're interested in. They can then add any number of ReportFields to that report and, when the report runs, it will call the data_method (the name of a property) on each instance of the model in the db.

The bit I'm having trouble with is defining which properties the users can have access to. I need to have a way of creating a load of ReportFields with certain data_methods for each model. But I don't want to create them by hand - I want it to work in a similar way to the way Permissions work in Django, if that's possible, like this:-

class MyModel(models.Model):
    class Meta:
        data_methods = (
            ('property_name_1', 'Property Name 1'),
            ('property_name_2', 'Property Name 2'),
            etc.
        )

From reading the source code, Django seems to run a management command after every migration on that model to make sure the model permissions are created. Is that the only way to do this? Am I going in the right direction here, or is there a better way?

0 Answers
Related