Удаление объекта базы данных с помощью кнопки в компоненте Vue
Я использую Django в качестве бэкенда и использую VueJS через Vite для фронтенда. В настоящее время я делаю GET запрос на данные через "api/recipes". Я хочу добавить кнопку в компонент Vue, чтобы сделать запрос DELETE для соответствующего рецепта. Формат не является проблемой, рецепты могут отображаться в виде списка, каждый из которых имеет свою кнопку для простого DELETE. Идея заключается в использовании API fetch, однако логика удаления объекта из бэкенда мне непонятна
App.vue
<template>
<div>
<button @click="fetchRecipes">Fetch Recipes</button>
<div>
<ul>
<li v-for="recipe in recipes">
{{ recipe.name }}
<span v-if="!recipe.popular">(Not very popular!)</span>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
recipes: [],
}
},
methods: {
async fetchRecipes() {
// Perform an Ajax request to fetch the list of recipes
let response = await fetch("http://localhost:8000/api/recipes/")
let data = await response.json()
this.recipes = data.recipes
}
}
}
</script>
urls.py
from django.contrib import admin
from django.urls import path
from mainapp.views import index, recipes_api
urlpatterns = [
path('', index),
path('api/recipes/', recipes_api),
]
models.py
from django.db import models
class Recipe(models.Model):
name = models.CharField(max_length=350)
popular = models.BooleanField(default=False)
def __str__(self):
return self.name
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'popular': self.popular,
}
views.py
from django.shortcuts import render
from django.http import HttpRequest, HttpResponse, JsonResponse
from mainapp.models import Recipe
def index(request: HttpRequest) -> HttpResponse:
title = "My App"
return render(request, "mainapp/index.html", {
'title': title,
'n': Recipe.objects.all().count()
})
def recipes_api(request):
if request.method == 'GET':
return JsonResponse({
'recipes': [
recipe.to_dict()
for recipe in Recipe.objects.all()
]
})