繁体   English   中英

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

[英]How to insert data to django database from views.py file?

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

有关我正在使用的更多解释:

  • 蟒蛇 3.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

从 niloofar.views 导入发送

url(r'^index/', 发送),

我想在加载页面索引时,发送函数工作并将数据插入数据库。

这是行不通的。 当我刷新索引页面时,它没有给出任何错误,也没有发生任何事情,没有任何内容发送到数据库。 我认为在我尝试插入数据的方式中存在语法错误。

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

从 book.models 导入 Publisher

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

p.save()

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

你的问题很不清楚。 您可能应该阅读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')

您只需创建一个模型的实例并保存即可。 假设你有一个文章模型:

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))

一个简单的方法是使用 create 函数。 通过提及字段名称及其值。 以下图示代码可帮助您将数据从 views.py 插入数据库并将数据库内容显示到 html 页面中。

假设我们有一个看起来像这样的表

Name      Age     Marks
Bunny      4       10
Tanishq    12      12

models.py 看起来像这样

from django.db import models

# Create your models here.
class Student(models.Model):

    student_name = models.CharField(max_length = 120)
    student_age = models.IntegerField()
    student_marks = models.IntegerField()

所以 views.py 看起来像

from django.shortcuts import render
from .models import Student    # Student is the model class defined in models.py

# Assuming the data to be entered is presnet in these lists
stud_name = ['Aman', 'Vijay']
stud_age = [13, 12]
stud_marks = [20, 22]

def my_view(request, *args, **kwargs):
    
    # Iterate through all the data items
    for i in range(len(stud_name)):

        # Insert in the database
        Student.objects.create(Name = stud_name[i], Age = stud_age[i], Marks = stud_marks[i])


    # Getting all the stuff from database
    query_results = Student.objects.all();

    # Creating a dictionary to pass as an argument
    context = { 'query_results' : query_results }

    # Returning the rendered html
    return render(request, "home.html", context)


下面应该是home.html文件,显示所有输入的数据

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>

<body>
<h1>HOME</h1>

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Marks</th>
      
    </tr>
    {% for item in query_results %}
        <tr> 
            <td>{{ item.student_name }}</td>
            <td>{{ item.student_age }}</td>
            <td>{{ item.student_marks }}</td>
            
        </tr>
    {% endfor %}
</table>

</body>
</html>


插入所需的以下更改,否则您将收到类型错误

Student.objects.create(stud_name =stud_name[i],stud_age =stud_age[i],stud_marks =stud_marks[i])

你可以试试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM