Retrieve the values of a particular key from your Django queryset JSON data and then seamlessly send them over to VueJS

I recently developed a web app using Django2 with Vue for the frontend. I encountered an issue in passing all values of a specific key from JSON data to a JavaScript dictionary value on the frontend. Despite trying to use the += operator to add the data, I failed to retrieve the desired information. Only the first row seemed to work, while the rest were not displayed in the table.

View.py:

def Browse_and_adopt(request):
query_results_book = Title.objects.all()
query_results_book_json = serializers.serialize('json', query_results_book)
return render(request, 'main.html', {"query_results_book_json": query_results_book_json})

main.html: {{ row.title }} {{ row.author }}

    <script>
          var query_results_book = {{ query_results_book_json|safe}};

    var book_row = {title: query_results_book[0].fields.title, author: query_results_book[0].fields.author };

    for (var i=1; i < query_results_book.length; i += 1){
        book_row += {title: query_results_book[i].fields.title, author: ''};
    }


    const app = new Vue({
        el: '#app',
        data:() => ({
            filter: '',
            rows: [book_row]
        }),
</script>

sample json:

{author: "Bill Gates", title: "test"}

Is there a way to effectively pass all data from this JSON file to vueJS?

Answer №1

The issue arises when attempting to retrieve a List of Titles from query_results_book_json and then treating it as a single item in:

var book = {title: query_results_book_json.title, author: query_results_book_json.author};

To solve this problem, you must either iterate through the results to find the specific book you are looking for, or adjust the query to only return the desired book.

UPDATE:

You may consider adding this snippet:

<script>
    var query_results_book = {{ query_results_book_json|safe}};
    var book = query_results_book[0];
</script>

UPDATE 2 (with example additions):

To access the keys of these dictionaries, you will need to use the [''] notation.

For instance, to extract the title of the first book using JavaScript, you would do something like this:

query_results_book[0]['title']

You can test this by logging a for loop similar to this:

<script>
for (let i = 0; i < query_results_book.length; i++) {  
   console.log(query_results_book[i]['title'])
}
</script>

Answer №2

When working with a JSON object, you can use the following code snippet:

<div v-for="(item, key) in jsonData" :key="key">
    <p>{{key}} : {{ item }}</p>
</div>

This will display the keys of the jsonData along with their respective items.

If you need to apply conditions based on specific keys, you can utilize the key variable within the loop to implement your logic.

For selectively displaying items linked to certain keys:

<div v-for="(item, key) in jsonData" :key="key">
    <div v-if="key === 'title'">
    <p>{{ item }}</p>
    </div>
</div>

For more insights on similar operations with Vue.js, check out this resource: Extracting text from error objects and manipulating them in Vue template.

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

Displaying a div based on the response after it is received using an if/else statement

In my form, each question is on a separate page (div), with the ability to show and hide pages. If a user receives a response from the API with a status of "accepted", they are redirected to a URL. I'm currently trying to display a div if their status ...

How to access data from a child component in a Vue 3 template

Within my project, there are three Vue components that utilize the Composite API with the setup option. My goal is to access data within a nested tree structure. The code below provides a simplified version of what I am trying to achieve. The application ...

Analyze the length of time and provide a percentage of similarity

Is it possible to compare two durations and calculate the percentage of similarity? Suppose I have a reference duration, as well as a second duration that needs to be compared with the first one. There is an 8% tolerance level, meaning that the second du ...

Is it possible to dynamically add an id or class to an element using document.createElement in JavaScript?

As a beginner in the world of JavaScript, I understand that the code structure I have used here may not be ideal for real-world applications. However, I am using it to practice my understanding of for loops and fetching JSON data. My main query is whether ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

Attempting to display a grid of product listings using a Websocket connection and an Express server

Recently, I attempted to create a live table of products using websockets for real-time updates. While I am new to this concept, I decided to upgrade an old project with websockets. Unfortunately, my attempts were unsuccessful, which is why I am seeking he ...

Tips on accessing information from a JSON file

I am facing an issue while trying to extract data from a JSON object that was passed from the servlet. The keys in my JSON object are numbered, and I need to append these numbers to the names of the keys. The structure of my response is as follows: {"sha ...

Ways to resolve a blank outcome in the $scope selection choices list?

Currently, I am utilizing AngularJS to create a select dropdown field populated with options from an array. The end user has the ability to add options via an input box. While the $scope successfully adds to the array, the dropdown select box displays "und ...

What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome. l ...

Addressing ESLint and TypeScript Issues in Vue.js with Pinia: A comprehensive guide

Experiencing difficulties with Vue.js + Pinia and need assistance to resolve these issues. Error: 'state:' is defined but never used. Here is the snippet of code located in @/stores/user.ts. import { defineStore } from 'pinia' export ...

Gradually vanishing words while they glide across the screen

I want to achieve a similar effect seen in the game A Dark Room. The text in the game serves two purposes which I am trying to replicate: The new text is added above the old text instead of below it, pushing the older text down the page as the game progr ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

Currently, I am developing a customized stylesheet specifically designed for Internet Explorer versions 10 and 11

Is it possible to utilize this straightforward script for identifying IE versions 10 and 11? if($.browser.version == 11.0 || $.browser.version == 10.0) { $("body").addClass("ie"); } ...

mongodb cannot locate the schema method within the nested container

Trying to access a method of a schema stored inside a mixed container has presented a challenge. The scenario is as follows: var CaseSchema = mongoose.Schema({ caseContent : {}, object : {type:String, default : "null"}, collision : {type : Boo ...

Tips for modifying the content displayed on a v-list in Vue.js dynamically

I am looking to create a dynamic list that displays data based on the selected key. The list will contain multiple items with different keys, and I want the flexibility to choose which data to display without hardcoding the actual key value. <template&g ...

establish expiration date for image

On my e-commerce site, users upload images to customize product items, such as adding their photo to a cake. I'm curious if there's a way to automatically delete these images after a certain expiry date. Is it possible to implement an automatic ...

What are the differences between using the open prop and conditionally rendering a Material-UI Modal component?

Is there a difference in using the open prop or conditionally rendering Material-UI's Modal component and its built components? The closing transition may be lost, but are there any performance advantages when dealing with multiple Modals? Example wi ...

The res.download() function in Express is failing to deliver the accurate URL to the client

When trying to utilize the res.download() method for downloading specific files from a server, there is an issue where triggering the res.download does not redirect the client to the correct URL. The files intended for download are located in a directory s ...

Configuring babel-loader in webpack for optimal HMR functionality

Recently, I encountered an issue while trying to add Hot Module Replacement (HMR) to my project. Despite the console showing that HMR was enabled and detecting changes in files, the view was not re-rendering. The console would display: [HMR] Updated modul ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...