In Django, the value field in JSON data has been merged with the field name to create concatenated field

I'm attempting to use Django, Ajax, and JSON to retrieve a string, but I'm encountering a problem where the JSON output includes field names instead of just values. Instead of getting only the value of the field, it returns something like [{'field_name': value}] as the complete string. When I check the console, I see: {'field_name': "[{'field_name': value}]"}

Below is the code I have written:

def drugsanddoses(request):
    drugIdentifier = request.POST.get('drugID')

    drug_group = Antiepileptics.objects.get(name=drugIdentifier)
    drug_name = RiskCalculator.objects.filter(drug_name=drug_group).values('drug_name')
    l_dose = RiskCalculator.objects.filter(drug_name=drug_group).values('l_dose')   
    h_dose = RiskCalculator.objects.filter(drug_name=drug_group).values('h_dose')   
    pubmed_id = RiskCalculator.objects.filter(drug_name=drug_group).values('pubmed_id') 
    updated = RiskCalculator.objects.filter(drug_name=drug_group).values('updated') 

    data = {}

    try:
        data['drug_name'] = str(drug_name)
        data['l_dose'] = str(l_dose)
        data['h_dose'] = str(h_dose)
        data['pubmed_id'] = str(pubmed_id)
        data['updated'] = str(updated)

    except:
        raise Http404

    print(data)

    return JsonResponse(data, safe=False)

Answer №1

It is important to note that the behavior you are encountering is expected when using str(queryset) on a values() query in Django's ORM. The values method returns a list of dictionaries, so if you only require the values, consider using:

RiskCalculator.objects.filter(drug_name=drug_group) \
                      .values_list('drug_name', flat=True).distinct()

You can refer to the Django documentation for more information on values and values_list.

In addition, there is no need to use str() on each query as you will ultimately need to serialize the Python data structure into JSON for better handling in JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a combination of PHP and jQuery, certain checkbox options were dynamically deactivated

<input type="checkbox" name="pref[]" value="red//fuji" />Fuji <input type="checkbox" name="pref[]" value="red//pinklady" />Pink Lady <input type="checkbox" name="pref[]" value="red//reddelicious" />Red Delicious <input type="checkbox" ...

The Analog Clock is unable to access the property of null

I'm struggling to understand what's wrong here. The querySelector doesn't seem to be functioning correctly as I keep encountering the error "cannot read the property of null" on line 10 of my JavaScript code. const deg = 6; const hr = docum ...

Scrapy error: Why can't I use strings as indices instead of integers?

I developed a web crawler to extract data from a news website: # -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from items import CravlingItem import re class CountrySpi ...

Learn how to create text animations using CSS triggered by a scroll event listener

I'm looking to create a text animation similar to the one on this website: They have 3 keyframes for two types of animations: Left to Right and Right to Left. The RTL animation starts at 164vh, while LTR starts at -200vh. These text animations only ...

document.addEventListener versus $().on

Recently, I came across an odd behavior while trying to add event listeners to the document. Strangely, when adding listeners to HTMLElements, everything worked smoothly, but for some reason, adding a listener to the document did not have any effect. Howev ...

Creating a JSON schema in JavaScript using an already established JSON framework

I have a json structure stored in a variable called "data" that looks like this: { "SearchWithMasterDataDIdAndScandefinitionDAO": [ { "dateDm_id": 20120602, "issueValue": "ELTDIWKZ", "scanName": "Company Stored as Person (Give ...

Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required... <button type="button" id= ...

Unleashing the Power of Python for Unraveling Insights from

I've been given a task to use Python for extracting data from a JSON file. The JSON file I have looks like the following: {"votes": {"funny": 15, "useful": 48, "cool": 18}, "user_id": "JkeCKyEaQlbLd9uZYl4DjA", "name": "LiiLii C.", "url": "http://www. ...

Traverse the JSON object list retrieved from the ASP.NET webservice

I have a web service in ASP.NET that returns a list of generics (List'<'Construct>) serialized as JSON using the following code: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1) ...

"Exploring the possibilities of RSelenium and Javascript together

While I have a strong understanding of R, my knowledge in javaScript and other languages is very limited. My goal is to access information from a publicly-available data set found here: . Specifically, I have a list of postal codes formatted as 'A1A1A ...

Sending a string of HTML elements to a Vue custom directive is causing problems with the eslint code analysis

I have developed two custom Vue directives to add an HTML element before or after another element. I provide an HTML string to the element where I apply the directive, but I am encountering an error in VS Code: Parsing error: unexpected-character-in-a ...

The Google Maps directions stay visible even when new routes are generated

Utilizing the Google Maps Javascript API V3 in my Android WebView has presented a new issue. When I request directions from point A to B, it displays correctly. However, when I switch the endpoints to go from A to C, the route from A to B does not disappea ...

There is no response provided by the function

Here is the code for inserting data into the database. However, it seems to be going into the else section as the response is empty. I have checked by alerting the response, but it remains empty. // Function to add donation via AJAX function ccjkfound ...

The Eclipse Phonegap framework is experiencing difficulty in loading an external string file with the jquery .load function

A basic index.html file has been created to showcase a text string from the test.txt file by utilizing the .load function from the jQuery library. The goal is to insert the textual content into an HTML (div class="konten"). The provided HTML script looks ...

Understanding Namespacing in Vuex with Vue.js

Trying to organize modules' getters, mutations, and actions with namespacing can be a bit challenging. I came across this document, but it didn't provide clear enough information for me. // types.js // Constants for namespacing getters, actio ...

Parsing DXF files using only plain JavaScript

Currently, I am immersed in a CNC project and aiming to convert DXF files into objects using JS. Initially, I attempted using SVGs but the results were not as expected - instead of shapes, the drawings exported as lines (e.g., a square appearing as four se ...

The customized Vaadin component with a tag is missing from the MainView layout

I am attempting to integrate my custom vis component into the MainView VerticalLayout. However, it is appearing above the layout and the layout itself contains an empty component tag. Custom component code In this section, I have labeled my component as " ...

Django's double 'extends' feature causes issues with user authentication

Hey there! I'm encountering a minor issue with the template double extend system. Here's how my scheme is set up: base.html ---> index.html ---> something.html After logging in to the site, I notice that I have access to all invisible blo ...

Following the content update via Ajax, the functionality of jQuery is experiencing glitches

My content slider works well on the first page of ajax loaded content. However, when I navigate to the next page from ajax loaded content and try to update the sliding animation for newly loaded future content using #readyslider, the slider starts glitchin ...

Generate unique div elements randomly using jQuery and Javascript to populate a container

My website has a section that spans 100% width and is 450 pixels tall. This is the HTML structure... <section class="interactive-banner"> <figure></figure> </section> I am aiming for each 'figure' element to be 150 ...