2

I am using Django 1.5.3 and PostgreSQL for my project. There are CIDR type fields in my tables and I wanted to model it in Django. I am using a CIDRField like ;

class CIDRField(models.Field):
    def __init__(self, *args, **kwargs):
        super(CIDRField, self).__init__(*args, **kwargs)

    def db_type(self, connection):
        return "CIDR"

    def to_python(self, value):
        return str(value)

    def get_db_prep_value(self, value, connection, prepared=False):
        # Convert value to pure network address to prevent
        # PostgreSQL exception
        if IP.prefix(value):
            return IP.prefix(value).first.prefix

When I query on the table with the CIDRField, I must use raw instead of filter;

select * from ip_table where ip<<'0.0.0.0/0'

Bu I also have another fields that is non CIDRField and I dont want to construct all queries about this table with raw. There is also no way I see to use both of them.

Maybe I can customize CIDRField more than that and I can use filter instead of raw to query on CIDRField. For example can I customize gt, gte, lt or lte lookup functions?. Can they be looking for <<,<<=,>>,>>= instead of <,<=,>,>=. Can I customize this operators in Django?

Thank you.

Chris Travers
  • 25,424
  • 6
  • 65
  • 182
Ahmet DAL
  • 4,445
  • 9
  • 47
  • 71

0 Answers0