python - django自定义属性返回过滤字段

标签 python django django-models

在 django 应用程序中,使用现有数据库,我使用 inspectdb 构建模型:

  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'

我添加了 savedelete 方法,因为这应该是一个只读模型。

其中一个字段是 sensor,它定义了不同的“传感器”(例如 BAT、ANE 等)的字符串。我想要拥有这样的特性:

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

我怎样才能做到这一点?

最佳答案

您可以创建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

并像这样使用它:

batteries = Sensorparser.batteries.all()

关于python - django自定义属性返回过滤字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39063340/

相关文章:

python - TKinter 获得单选按钮值的问题

Python:如何进行此字符串操作

python - GeoDjango 查询 : all point that are contained into a multi polygon

python - django-rest-framework ManyToManyField 创建和更新

python - 将 Flask-login 与 Flask-admin 一起使用

python - 带阴影线的 matplotlib 自定义图例

python - 我如何测试用户是否具有查看权限

django - Django:模型验证错误ManytoManyField

mysql - Django 查询集 : Why can't I filter an annotated QuerySet?

python - Slugify 未将标题保存为 slug Django 2 : NoReverseMatch error