Django: insert row into database

I am new to Django. I created a table by inserting a model in models.py .

Now I want to insert a row into the Dodavatel database Dodavatel . I know that I need to create an object with attributes in the form of columns. But I don’t know where to put this code. In 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 to insert the line:

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

Where should I put this code?

+6
source share
2 answers

If you only want to quickly test your models, you can run the interactive shell and execute your code there.

 python manage.py shell 

The above command launches an interactive python shell initialized with your Django project settings.

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 using this code directly inside the view. Instead, to create an element, I would use a class-based view, like CreateView .

+14
source

Well, you could put this in your views.py file in functions called "new" or maybe "paste". This page shows how to create views and attach link URLs to it.
This is a blog application that I created using Django. Hope you find the link to link -.

-1
source

Source: https://habr.com/ru/post/969853/


All Articles