Django框架 靓号管理(增删改查)
以下是一个简单的Django模型(Meihao)的增删改查操作示例:
首先,确保你已经创建了Django模型(Meihao)。
# models.py
from django.db import models
class Meihao(models.Model):
name = models.CharField(max_length=100)
number = models.IntegerField()
description = models.TextField()
然后,在视图(views.py)中编写对应的函数来执行增删改查操作:
# views.py
from django.shortcuts import render
from .models import Meihao
# 创建
def create_meihao(request):
name = request.POST.get('name')
number = request.POST.get('number')
description = request.POST.get('description')
meihao = Meihao.objects.create(name=name, number=number, description=description)
return render(request, 'meihao_list.html', {'meihao': meihao})
# 读取
def list_meihao(request):
meihaos = Meihao.objects.all()
return render(request, 'meihao_list.html', {'meihaos': meihaos})
# 更新
def update_meihao(request, pk):
meihao = Meihao.objects.get(pk=pk)
meihao.name = request.POST.get('name')
meihao.number = request.POST.get('number')
meihao.description = request.POST.get('description')
meihao.save()
return render(request, 'meihao_detail.html', {'meihao': meihao})
# 删除
def delete_meihao(request, pk):
meihao = Meihao.objects.get(pk=pk)
meihao.delete()
return render(request, 'meihao_list.html', {'meihaos': Meihao.objects.all()})
最后,在URLs配置(urls.py)中指定路由:
# urls.py
from django.urls import path
from .views import create_meihao, list_meihao, update_meihao, delete_meihao
urlpatterns = [
path('create/', create_meihao, name='create_meihao'),
path('list/', list_meihao, name='list_meihao'),
path('update/<int:pk>/', update_meihao, name='update_meihao'),
path('delete/<int:pk>/', delete_meihao, name='delete_meihao'),
]
这个简单的示例展示了如何在Django中创建、读取、更新和删除一个名为"Meihao"的对象。在实际应用中,你还需要创建对应的HTML模板来显示数据和接收用户输入。
评论已关闭