开发者

How to query a Django model defining a IP range with two 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 certain IP, how can I get all the ranges that match this specific IP using the Django开发者_JS百科 models?

If I were using raw SQL, I would use the database's bitwise operators, but the Django ORM doesn't support those.


The QuerySet API in Django 1.0 now includes the 'extra' method, described here in the Django docs. The extra method allows you to pass custom WHERE clauses to your QuerySet, which should allow you to use the bitwise comparison you need.


To do faster query fitting the range you'd better store lower and upper IP of range as integer. Then selection of needed objects should be as simple as Range.objects.filter(ip_low__le=ip, ip_up__ge=ip).


I would recommend using python's iptools :

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜