Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - How to store values from Many to Many Django field in JSON response?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to use Django's serializers for serializing data for API responses; they're not really meant for that either since the internal structure of your model can differ greatly from what you want to publish. Many folks tend to use Django REST Framework, which has a more flexible way to declare serialization.

That aside, your function is rather strange, since

  • you're iterating over all products in your database for no reason
  • you're checking whether a product exists after you've already .get()ed it (which would fail if it didn't exist)

I think you're looking for something like

def retrieve_product(request):
    product = Product.objects.get(id=request.GET["name"])
    data = {
        "name": product.name,
        "detail": product.detail,
        "price": product.price,
        "id": product.id,
        "image": product.product_image.url,
        "sizes": list(product.size.values_list("name", flat=True)),
    }
    return JsonResponse(data)

Edit

As discussed, to add a field for the default size (if any),

def retrieve_product(request):
    product = Product.objects.get(id=request.GET["name"])
    size_names = list(product.size.values_list("name", flat=True))
    data = {
        "name": product.name,
        "detail": product.detail,
        "price": product.price,
        "id": product.id,
        "image": product.product_image.url,
        "sizes": size_names,
        "default_size": next(iter(size_names), None),
    }
    return JsonResponse(data)

should do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...