Python Django:将行插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23868958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:34:16  来源:igfitidea点击:

Django: Insert row into database

pythonmysqldjangoinsert

提问by Milano

I'm new in Django. I've created a table by insert model into models.py.

我是 Django 的新手。我通过将模型插入到models.py.

Now, I want to insert a row into the database - table Dodavatel. I know, that I have to create an object with attributes as columns. But I don't know where should I put this code. In models.py?

现在,我想在数据库表中插入一行Dodavatel。我知道,我必须创建一个属性作为列的对象。但我不知道我应该把这段代码放在哪里。在models.py

This is my model:

这是我的模型:

class Dodavatel(models.Model):
    nazov = models.CharField(default='', max_length=255)
    dostupnost = models.IntegerField(default=0)

This is the code for inserting a row:

这是插入一行的代码:

p = Dodavatel(nazov='Petr', dostupnost=1)
p.save()

Where should I put this code?

我应该把这段代码放在哪里?

采纳答案by Luca

If you only want to quick test your models you can start an interactive shell and execute your code there.

如果您只想快速测试您的模型,您可以启动一个交互式 shell 并在那里执行您的代码。

python manage.py shell

The above command starts a python interactive shell initialized with your Django project settings.

上面的命令启动了一个用你的 Django 项目设置初始化的 python 交互式 shell。

Then you can do something like:

然后你可以做这样的事情:

from your_app_name.models import Dodavatel
p = Dodavatel(nazov='Petr', dostupnost=1)
p.save()

I do not recommend to use that code directly inside a view. Instead to create an item I would use a class based view like CreateView.

我不建议直接在视图中使用该代码。而不是创建一个项目,我会使用一个基于类的视图,如CreateView.