1

I have a template (menu.html), and I am making an AJAX call with JavaScript. Then, I want to process that call (throughout the GET parameters) and make a query from Django's ORM. \

My JavaScript code is:

$.ajax("/showcart", {
        type: "GET",
        data: {
            product: product,
            type: product_type
        },
        success: function(response) {
            console.log("SUCCES SUCCESS SUCCESS")
            console.log(response);
        },
        error: function(resp) {
            console.log("ERROR ERROR ERROR!")
            console.log(resp)
        }

    })

product is the name of my product, and product_type is the size of my product.
Then, in my views.py, I handle this call with:

def showcart(request):
    product = request.GET['product']
    if request.GET['type'] == "small":
        size = f"{request.GET['type']}_price"
    elif request.GET['type'] == "large":
        size = f"{request.GET['type']}_price"
    else:
        size = "price"

    product_name = product.split("-")[0]
    product_id = product.split("-")[1]

    return JsonResponse(
        {
        "product_name": product_name,
        "product_id": product_id,
        "size": size,
        "queryresult": "nothing here",
        }
    )

For example, product_name is "Sub" and I have a model in models.py called Sub. My goal is querying the price, for instance, with the product_name. But, since it is a string type, Django doesn't allow me to do that. Does anyone know how this works?

Thanks,

Ege Hurturk
  • 693
  • 1
  • 10
  • 12
  • I find it unclear... Please show your `models.py`. Also, you said sthg about queryset but, there is no queryset. – Biplove Lamichhane Sep 05 '20 at 10:50
  • @BiploveLamichhane What I mean is, I get a `product_name` "Sub", and my model's name is Sub and has a field `price`. I want to use `product_name.objects.get(...)` but Django throws an error saying that `product_name` is a string. How can I use that variable when querying from `models.py`? – Ege Hurturk Sep 05 '20 at 10:52
  • 1
    Okay... now I get what you are asking. Does this help you https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object ? – Biplove Lamichhane Sep 05 '20 at 10:54

0 Answers0