如何从views.py文件向Django数据库插入数据?

2024-06-01 08:15:50 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从视图py文件中的函数向django数据库插入数据?python manage.py shell是插入的唯一方式吗?

关于更多的解释,我使用:

  • Python3.4
  • django 1.8.2公司
  • PyMySQL

例如:

型号.py:

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    city = models.CharField(max_length=60)

视图.py:

from django.http import HttpResponse
import pymysql
from books.models import Publisher

def send(request):
    p = Publisher(name='Apress', city='Berkeley')
    p.save()

网址.py

from niloofar.views import send

url(r'^index/', send),

我希望在加载页面索引时,send函数可以工作并将数据插入数据库。

它不起作用。它没有给出任何错误,也没有发生任何事情时,我刷新了索引页,没有发送到数据库。我认为在语法上有错误,在我试图插入数据的方式上。

让我注意到,即使我运行python manage.py shell时:

from books.models import Publisher

p = Publisher(name='Apress', city='Berkeley')

p.save()

不会向django数据库插入任何内容。


Tags: 数据django函数namefrompyimportsend
3条回答

你可以试试这个:

def myFunction(request):
    myObj = MyObjectType()
    myObj.customParameter = parameterX
    ...
    myObj.save()

您可以创建一个模型的实例并保存它。假设您有一个文章模型:

from django.http import HttpResponse
from django.template import loader

from .models import Article


def index(request):
    article = Article()
    article.title = 'This is the title'
    article.contents = 'This is the content'
    article.save()

    template = loader.get_template('articles/index.html')
    context = {
        'new_article_id': article.pk,
    }
    return HttpResponse(template.render(context, request))

你的问题很不清楚。你可能应该通过django-tutorial

但是您可以从视图将数据插入数据库。假设您有一个名为Foo的模型:

模型.py

class Foo(models.Model):
    name = models.CharField(max_length=100)

视图.py

from .models import Foo

def some_name(request):
    foo_instance = Foo.objects.create(name='test')
    return render(request, 'some_name.html.html')

相关问题 更多 >