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.

+2
python django django-models


source to share


3 answers


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.



+4


source to share


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)

.



+2


source to share


I would recommend using python iptools:

http://code.google.com/p/python-iptools/

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics