Search code examples
pythondjangomodels

Django getting model data where something > something else


With Django I have this model:

class downloads(models.Model):
date = models.CharField(max_length=50)
ip = models.ForeignKey(IPaddress)
partnum = models.ForeignKey(partnum)
user = models.ForeignKey(userinfo)
filename = models.CharField(max_length=128)
issueId = models.ForeignKey(issueInfo)

What I need to do is to get data from that table where the date is > date 1 and < date2

I know if I was using PHP I could query the db to do something like select * from downloads where date > date1 and date < date2 which would ofc give me a dataset to iterate through, How do I go about this using Django?

I am going to take a wild stab in the dark and ask is it something like this:

d = downloads.objects.get('Where date > date1 and date < date2')

or

d = downloads.objects.get(date=>date1,date<=date2)

I am very new to python and Django (started to learn it last week...) and any help would be brilliant.

Thanks

Edit: Thanks for the quick replys - worked out the answer to my new question


Solution

  • If you are using Django ORM then do the following:

    downloads = Downloads.objects.filter(date__range=(dat1, date2))
    

    or

    downloads = Downloads.objects.filter(date__gt=date1, date__lt=date2)
    

    This will filter your objects accordingly. __gt means "greater than" and __lt means "less than".

    Read the documentation for further clarification: https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter

    https://docs.djangoproject.com/en/dev/ref/models/querysets/#gt