我想在一个JSON字段中存储多个输入。
这是订单表,有一个"attribute_field"我想在这个字段中存储属性为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')
这里我没有做form save方法,但是让我解释一下我想做什么。
我想wrap SIZE, COLOR, PAPER CHOICE是单个JSON,并将其存储在模型的attribut_values字段中,但不知道怎么做,你能给我解释一下吗?
如果你的Django版本>= 3.1,你可以使用JSONField
,否则使用TextField
。像这样:
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})