Reputation: 129
I want to store multiple inputs in single JSON field.
this is the order table , there is a "attribute_field" I want to store the attributes in this field as JSON.
models.py
class Order(models.Model):
order_id = models.AutoField("Order ID", primary_key=True)
user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID")
prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID")
quantity = models.ImageField('Product Quantity', max_length=10, default=500)
attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False)
order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00)
views.py
def order(request, id):
if request.method == 'POST':
customer_id = request.user.user_id
product_id = id
try:
size = request.POST['size']
except MultiValueDictKeyError:
pass
try:
Colour = request.POST['Color']
except MultiValueDictKeyError:
pass
try:
Paper_Choice = request.POST['PaperChoice']
except MultiValueDictKeyError:
pass
return render(request, 'user/order.html')
here I have not done form save method, but let me explain what I want to do.
I want to wrap SIZE, COLOR, PAPER CHOICE is single JSON and store it in attribut_values field in model but don't know how to do, can you please explain it to me.
Upvotes: 0
Views: 937
Reputation: 6331
If your Django version >= 3.1, you can use JSONField
, otherwise use TextField
.
Something like this:
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Customer")
prod = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Product")
quantity = models.ImageField('Product Quantity', max_length=10, default=500)
attribute_value = models.TextField("Item Details JSON")
price = models.DecimalField(max_digits=8, decimal_places=2, default=0)
views.py
def order(request, id):
if request.method == 'POST':
customer = request.user
product_id = id
try:
size = request.POST['size']
except MultiValueDictKeyError:
pass
try:
Colour = request.POST['Color']
except MultiValueDictKeyError:
pass
try:
Paper_Choice = request.POST['PaperChoice']
except MultiValueDictKeyError:
pass
order = Order.objects.filter(user=customer, prod=product_id).first()
value = dict(size=size, Colour=Colour, Paper_Choice=Paper_Choice)
order.attribute_value = json.dumps(value)
order.save()
return render(request, 'user/order.html', {'order': order})
Upvotes: 1