6๐
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).
21๐
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.
- [Django]-Suppress "?next=blah" behavior in django's login_required decorator
- [Django]-Writing test cases for django models
- [Django]-Exception Value:failed to find libmagic. Check your installation in windows 7
10๐
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.
- [Django]-Download a remote image and save it to a Django model
- [Django]-Jquery and Django CSRF Token
- [Django]-Django: Initializing a FormSet of custom forms with instances
10๐
Using a custom field type is my preferred solution โ Iโd rather have a few lines of custom code than support an entire 3rd party library for a single field type. Tony Abou-Assaleh has a great solution, but wonโt work for newer versions of Django.
This is verified to work with Django 1.10.4
import json
from django.db import models
from django.core.serializers.json import DjangoJSONEncoder
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()
"""
def to_python(self, value):
if value == "":
return None
try:
if isinstance(value, str):
return json.loads(value)
except ValueError:
pass
return value
def from_db_value(self, value, *args):
return self.to_python(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 value
- [Django]-Django formset_factory vs modelformset_factory vs inlineformset_factory
- [Django]-Cleanest & Fastest server setup for Django
- [Django]-MySQL "incorrect string value" error when save unicode string in Django
4๐
If postgres is your backend, consider the hstore field which has native support from django
- [Django]-Alternative to the deprecated setup_environ() for one-off django scripts?
- [Django]-Serialize datetime to JSON
- [Django]-What is a Django "app" supposed to mean?
3๐
I think that I would create the field as models.CharField() and then encode the dictionary as a JSON string and save that string into the database. Then you can decode the JSON string back into a dictionary when you read it out.
- [Django]-Django: Best way to implement "status" field in modules
- [Django]-Invalid block tag : 'endblock'. Did you forget to register or load this tag?
- [Django]-Django unique_together with nullable ForeignKey
3๐
You can use serialization/deserialization from pickle module:
- [Django]-Heroku โ Handling static files in Django app
- [Django]-How to allow users to change their own passwords in Django?
- [Django]-Django.contrib.gis.db.backends.postgis vs django.db.backends.postgresql_psycopg2
1๐
If using PostGres you can store it in natively supported JSON field:
https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#jsonfield
Otherwise Iโd recommend @ramiro answer with 3rd party lib https://stackoverflow.com/a/16437627/803174
- [Django]-Change a Django form field to a hidden field
- [Django]-Django 1.5 โ How to use variables inside static tag
- [Django]-How to get user permissions?
1๐
according to Django doc you can use :
from django.contrib.postgres.fields import JSONField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = JSONField()
def __str__(self):
return self.name
and create with this :
Dog.objects.create(name='Rufus', data={
'breed': 'labrador',
'owner': {
'name': 'Bob',
'other_pets': [{
'name': 'Fishy',
}],
},
})
I hope this can assist you.
- [Django]-Reverse for '*' with arguments '()' and keyword arguments '{}' not found
- [Django]-Django: signal when user logs in?
- [Django]-Coverage.py warning: No data was collected. (no-data-collected)