John John - 3 months ago 24
Python Question

django custom property to return filtered field

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

inspectdb
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):
return

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

class Meta:
managed = False
db_table = 'sensorParser'


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

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

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


How can I accomplish this?

Answer

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()
Comments