07/30/09

English (US)   Barcode (GTIN) field for Django  -  Categories: Programming  -  @ 10:09:55 am

It was pretty simple in the end. You can find the item with and without zero padding.

Code:

from django.db import models
class BarcodeField(models.IntegerField):
    __metaclass__ = models.SubfieldBase
    
    def to_python(self, value):
        if value is None: return
        return "%014.0d" % value
    
    def get_db_prep_save(self, value):
        if value is None: return
        return int(value)

And using it:

Code:

from project import cfields
class Product(models.Model):
    status = models.IntegerField()
    barcode = cfields.BarcodeField()

Code:

>>> eeepc = Product(name="ASUS Eee PC 1005HA-PU1X-BK 10.1-Inch Black Netbook", status=1)
>>> eeepc.barcode=304
>>> eeepc.barcode
'00000000000304'
>>> eeepc.save()
>>> eeepc.barcode
'00000000000304'
>>> eeepc.barcode=39584
>>> eeepc.save()
>>> Product.objects.get(barcode="00000000039584")
<Product: ASUS Eee PC 1005HA-PU1X-BK 10.1-Inch Black Netbook>
>>> Product.objects.get(barcode="00000000039584").barcode
'00000000039584'
>>> Product.objects.get(barcode=39584).barcode
'00000000039584'

powered by b2evolution free blog software

Contact the admin - Credits: blog software | web hosting | monetize