How to query Django model defining IP range with 2 int fields (IP, mask)
I have:
class Range(models.Model):
ip = models.IntegerField() # as produced by socket.inet_aton + struct.unpack
mask = models.IntegerField()
Given a specific IP, how can I get all ranges corresponding to that specific IP using Django models?
If I was using raw SQL I would use bitwise database operators, but Django ORM does not support them.
The QuerySet API in Django 1.0 now includes an "extra" method, described here in the Django docs. An additional method allows you to pass custom WHERE clauses to your QuerySet, which should allow you to use the bitwise comparison that you need.
In order to make a faster query suitable for a range, you'd better store the lower and upper IPs of the range as integers. Then the selection of the required objects should be as simple as Range.objects.filter(ip_low__le=ip, ip_up__ge=ip)
.
I would recommend using python iptools:
http://code.google.com/p/python-iptools/