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'
Leave a comment

Comments:

No Comments for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))

You can just use your OpenID to provide your name, e-mail and url.

Pingbacks:

No Pingbacks for this post yet...

powered by b2evolution free blog software

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