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!
Saving objects. To save an object back to the database, call save() : Model.
A model in Django is supposed to correlate to a table in the database, so that each field in the model will actually be a field in the table for that model. To achieve what you're trying to do, you need to create a second model, which will be the object you want to store.
You can't sort a dictionary, you can sort representation of a dictionary. Dictionary has a random ordered members. I hope this helps. If i'm doing this: sorted_dict = sorted(data['scoruri'].
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.
One convenient way to store a JSON representation in a model is to use a custom field type:
class JSONField(models.TextField):
"""
JSONField is a generic textfield that neatly serializes/unserializes
JSON objects seamlessly.
Django snippet #1478
example:
class Page(models.Model):
data = JSONField(blank=True, null=True)
page = Page.objects.get(pk=5)
page.data = {'title': 'test', 'type': 3}
page.save()
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if value == "":
return None
try:
if isinstance(value, basestring):
return json.loads(value)
except ValueError:
pass
return value
def get_db_prep_save(self, value, *args, **kwargs):
if value == "":
return None
if isinstance(value, dict):
value = json.dumps(value, cls=DjangoJSONEncoder)
return super(JSONField, self).get_db_prep_save(value, *args, **kwargs)
I saved this utils/fields.py and in my model from utils.fields import JSONField
. There are many more goodies in the django-annoying app, which is where this snippet came from.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With