John John - 1 year ago 98
Python Question

django custom property to return filtered field

In a django app, with an existing database, I've used

to build a model:

class Sensorparser(models.Model):
""" a read-only implemenation to access the MeshliumDB """
id_wasp = models.TextField(blank=True, null=True)
id_secret = models.TextField(blank=True, null=True)
frame_type = models.IntegerField(blank=True, null=True)
frame_number = models.IntegerField(blank=True, null=True)
sensor = models.TextField(blank=True, null=True)
value = models.TextField(blank=True, null=True)
timestamp = models.DateTimeField()
raw = models.TextField(blank=True, null=True)
parser_type = models.IntegerField()

def save(self, *args, **kwargs):

def delete(self, *args, **kwargs):

class Meta:
managed = False
db_table = 'sensorParser'

I added the
methods because this should be a read-only model.

One of the fields is
which defines strings for different, well, "sensors" (e.g. BAT, ANE, etc.). I would like to have a property like this:

def battery()
return self.sensor.objects.filter(sensor='BAT')

How can I accomplish this?

Answer Source

You can create custom manager:

class BatteryManager(models.Manager):
    def get_queryset(self):
        return super(BatteryManager, self).get_queryset().filter(sensor='BAT')

class Sensorparser(models.Model):
    batteries = BatteryManager()
    # etc

And use it like this:

batteries = Sensorparser.batteries.all()