I'm trying to access data from a model which contains a many-to-many field.
My main model is Product.
class Product(models.Model):
id = models.IntegerField(unique=True, auto_created=True, primary_key=True)
name = models.CharField(max_length=80, unique=True)
price = models.CharField(max_length=100, null=True)
size = models.ManyToManyField(Size)
size2 = models.CharField(max_length=50,null=True)
detail = models.CharField(max_length=1000, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
product_image = models.ImageField(upload_to='product_image/', null=True, blank=True)
category = models.ForeignKey(Procategory,on_delete=models.CASCADE, related_name='products',null=True)
class Meta:
ordering = ('-date_created',)
def __str__(self):
return self.name
Model for Size field is:
class Size(models.Model):
name = models.CharField(max_length=200,
db_index=True,null=True)
def __str__(self):
return self.name
I want to access Product size in my view function and want to store the sizes in JSON response.
My view function:
def validate_username(request):
username = request.GET.get('name', None)
product = Product.objects.get(id=username)
result = Product.objects.all()
for size1 in result:
a =size1.size.all()
data1 = serializers.serialize('json', product.size.all())
data = {
'is_taken': Product.objects.all().filter(id=username).exists(),
'name': product.name,
'detail': product.detail,
'price': product.price,
'id': product.id,
'image': product.product_image.url,
'size':data1
}
if data['is_taken']:
data['error_message'] = 'A user with this username already exists.'
data['name2'] = 'hi...'
return JsonResponse(data)
My Js code for size:
var b= data.size;
document.getElementById("product-size").innerHTML = b;
The result:
[{"model": "medical_store_app.size", "pk": 1, "fields": {"name": "300ml"}}, {"model": "medical_store_app.size", "pk": 2, "fields": {"name": "500g"}}]
But I just want to show size that are "300ml" and "500g".
How can it be done?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…