On Aug 8, 8:25 pm, BenW <benwil...@gmail.com> wrote:
> Hello,
>
> I am working with a legacy database that stores IP addresses as 32bit
> packed integers.  Is there a way I can use 'managed' attributes with
> filter() and exclude() etc?  Please see example below:
>
> Thanks!
>
> class Host(models.Model):
>
>     id = models.AutoField(primary_key=True, db_column='id')
>     _ipaddr = models.PositiveIntegerField(db_column='ip_address')
>
>     def _get_ipaddr(self):
>         ''' Convert 32bit packed IP to string quad
>         '''
>         return socket.inet_ntoa(struct.pack('L', self._ipaddr))
>
>     def _set_ipaddr(self, ip):
>         ''' Convert string quad IP to 32bit packed
>         '''
>         self._ipaddr = struct.unpack('L', socket.inet_aton(ip) )[0]
>
>     ipaddr = property(_get_ipaddr, _set_ipaddr)
>
> Creating new Host objects with a string IP works:
>
> >> host = Host.objects.create(ipaddr='127.0.0.1')
>
> Getting the string IP from an existing Host object works:
>
> >> host.ipaddr
> '127.0.0.1'
>
> Filtering doesn't work:>> Host.objects.filter(ipaddr='127.0.0.1').count()
>
> FieldError: Cannot resolve keyword 'ipaddr' into field. Choices are:
> id, _ipaddr
>
>
>
> This is because filter() doesn't check for the attribute 'ipaddr'
> because it's not in _meta.local_fields or wherever
> I'd really like to be able to use 'managed' attributes for querying.
> Any way to do this?  I understand filter() has no way of knowing to
> first convert '127.0.0.1' to packed int before appying to _ipaddr in
> the current scenario, but I thought maybe there's a special field or
> kwarg I'm missing.

Rather than use getters and setters on  a standard field, you'd be
better off creating a custom field subclass. If you do that you can
define a get_db_prep_lookup method which converts the lookup value to
the value needed to search the database. See the documentation here:
http://docs.djangoproject.com/en/dev/howto/custom-model-fields/
- and remember to set the field's __metaclass__ to SubfieldBase,
otherwise the custom methods aren't used.
--
DR.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to