0

I am new to working with Django and postgres JSONFields. Using Django 1.11.1 The following view reports a

name 'snapshot__timestamp' is not defined

Model:

class Snapshot(models.Model):
    id = PGUUIDField(primary_key=True)
    snapshot = JSONField(help_text=("Snapshot of config tree values"))

View:

def get_queryset(self):
    if len(self.request.query_params) > 0:
        try:
            startdate = time.strptime(self.request.query_params.get('startdate', None),'%Y-%m-%d %H:%M:%S')
            enddate = time.strptime(self.request.query_params.get('enddate', None), '%Y-%m-%d %H:%M:%S')
            return Snapshot.objects.filter(Q(snapshot__timestamp>=startdate) & Q(snapshot__timestamp<=enddate))
        except Exception as e:
            print(e)
            logger.exception(e)  
            return Snapshot.objects.none()
    return Snapshot.objects.all()

Example json field entry:

{"tree": {"asdf": "values"}, "pollgroup": [1, 3], "timestamp": "2017-7-2 00:00:00"}

All of the examples I have found show the modelfield__json key in the query. What am I doing wrong?

Michaela Ervin
  • 702
  • 8
  • 25

1 Answers1

0

timestamp is a field of Snapshot. Use:

Snapshot.objects.filter(
    Q(timestamp__gte=startdate) & 
    Q(timestamp__lte=enddate)
)

Check Django documentation about field lookups.

alfonso.kim
  • 2,844
  • 4
  • 32
  • 37