Djangos database operations – Add, delete, change, and query

In this guide (and resources), we will refer to the following models,

from django.db import models

class Blog(models.Model) :
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self) :
        return self.name

class Author(models.Model) :
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self) :
        return self.name

class Entry(models.Model) :
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField()
    number_of_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self) :
        return self.headline
Copy the code

1 increase

There are two ways to create an object, initialize it with a keyword argument, and then call save() to add data to the database.

1) save

By creating a model class object, execute the object’s save() method to save it to the database.

>>> from .models import Blog
>>> book = Blog(
...         name='python',
...         tagline='ABCDEFG'
...     )
>>> blog.save()
>>> blog
Copy the code

2) create

Stored in the model class.objects.create().

>>> Blog.objects.create(
...         name='python2',
...         tagline='abcdefg'
...     )
Copy the code

Pay attention to

Save the ForeignKey and ManyToManyField fields *

Updating a ForeignKey field is done the same way you would save a normal field — just assign an instance of the correct type to the related field. This example updates the blog attribute for an instance of the Entry class, Entry, assuming that both the Entry and blog instances are saved in the database (so they can be retrieved below) :

>>> from blog.models import Blog, Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()
Copy the code

Updating the ManyToManyField field is a bit different — you use the add() method on the field to add a record to the association. This example adds Author instance Joe to the entry object:

>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)
Copy the code

2 modify

There are two ways to modify updates

1) save

Modify the properties of the model class object, and then execute the save() method

>>> blog = Blog.objects.get(name='hello') >>> blog.name = 'aaa' >>> blog.save() >>> blog <PeopleInfo: Aaa > # updates behind the scenesCopy the code

2) update

Using the model class.objects.filter().update() returns the number of affected rows

>>> Blog.objects.filter(name='abcdefg').update(name='python3')
1
Copy the code

3 remove

Typically, the delete method is named delete(). The method immediately deletes the object and returns the number of deleted objects and a dictionary containing the number of deleted object types. Example: There are two ways to delete

1) Delete model class object

>>> e.delete()
(1, {'weblog.Entry': 1})
Copy the code

You can also delete objects in batches. All Querysets have a delete() method, which deletes all members of the QuerySet.

For example, this deletes all Entry objects published in 2005:

>>> Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})
Copy the code
Entry.objects.all().delete()
Copy the code