How to store a dictionary in a Django database model's field

Radu Gheorghiu picture Radu Gheorghiu · Mar 13, 2012 · Viewed 43.1k times · Source

I need to save a dictionary in a model's field. How do I do that?

For example I have this code:

def create_random_bill(self):
    name_chars = re.compile("[a-zA-Z0-9 -_]")
    bill_name = "".join(random.choice(name_chars for x in range(10)))
    rand_products = random.randint(1,100)
    for x in rand_products:
        bill_products = 
    new_bill = Bill.new(name=bill_name, date=datetime.date, products=bill_products)
    new_bill.save()

What do I write for "bill_products=" so it saves some random products, from my Product model to this bill?

This is the bill's model description:

class Bill(models.Model):
    name = models.CharField(max_length=255)
    date = models.DateTimeField(auto_now_add=True)
    products = models.ManyToManyField(Product, related_name="bills")

And also the product's model description:

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.IntegerField()

If there's anything else i should add just leave a comment. Thanks!

Answer

ramiro picture ramiro · May 8, 2013

I just discovered the django-jsonfield package, which

is a reusable Django field that allows you to store validated JSON in your model.

Looks like a viable option to achieve what you want.