Radu Gheorghiu Radu Gheorghiu - 1 year ago 135
Python Question

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

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)

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 Source

Probably the cleanest thing to do would be to create another "Products" table and have a many-to-many relationship. (See here: https://docs.djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships . In the docs they use the example of a pizza having many toppings.)

The other option would be to serialize your bill_products. In that case, you'd do something like:

bill_products = json.dumps([rand_products])

This would be outside of the for loop (although, in your example above, rand_products is only a single value, so you'll need to fix that).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download